Chapter 7 Expressions and Statements Expressions Arithmetic - - PDF document

chapter 7 expressions and statements
SMART_READER_LITE
LIVE PREVIEW

Chapter 7 Expressions and Statements Expressions Arithmetic - - PDF document

Chapter 7 Expressions and Statements Expressions Arithmetic Expressions Conditional Expressions Relational Expressions Logical Expressions Operator Overloading Assignment Statement Control Structure Selection


slide-1
SLIDE 1

CSCI325 Chapter 7 Dr Ahmed Rafea 1

Chapter 7 Expressions and Statements

  • Expressions

–Arithmetic Expressions –Conditional Expressions –Relational Expressions –Logical Expressions –Operator Overloading

  • Assignment Statement
  • Control Structure

–Selection Statements –Multiple Selection Statement –Iterative Loops –Logically controlled Loops –User Controlled loops –Unconditional Branching –Guarded Commands

  • Exception Handling

–Ada Exception Handling –C++ Exception Handling –Java Exception Handling

slide-2
SLIDE 2

CSCI325 Chapter 7 Dr Ahmed Rafea 2

Arithmetic Expressions

  • Their evaluation was one of the motivations for the

development of the first programming languages

  • Arithmetic expressions consist of operators,
  • perands, parentheses, and function calls

Design issues for arithmetic expressions:

  • 1. What are the operator precedence rules?
  • 2. What are the operator associativity rules?
  • 3. What is the order of operand evaluation?
  • 4. Are there restrictions on operand evaluation

side effects?

  • 5. Does the language allow user-defined operator
  • verloading?
  • 6. What mode mixing is allowed in expressions?
slide-3
SLIDE 3

CSCI325 Chapter 7 Dr Ahmed Rafea 3

Arithmetic Expressions

A unary operator has one operand A binary operator has two operands A ternary operator has three operands Def: The operator precedence rules for expression evaluation define the order in which “adjacent”

  • perators of different precedence levels are

evaluated (“adjacent” means they are separated by at most one operand)

  • Typical precedence levels
  • 1. parentheses
  • 2. unary operators
  • 3. ** (if the language supports it)
  • 4. *, /
  • 5. +, -

Def: The operator associativity rules for expression evaluation define the order in which adjacent

  • perators with the same precedence level are

evaluated

slide-4
SLIDE 4

CSCI325 Chapter 7 Dr Ahmed Rafea 4

Arithmetic Expressions

  • Typical associativity rules:
  • Left to right, except **, which is right to left
  • Sometimes unary operators associate right to

left (e.g., FORTRAN)

  • APL is different; all operators have equal

precedence and all operators associate right to left Precedence and associativity rules can be

  • verriden with parentheses

Operand evaluation order

  • The process:
  • 1. Variables: just fetch the value
  • 2. Constants: sometimes a fetch from memory;

sometimes the constant is in the machine language instruction

  • 3. Parenthesized expressions: evaluate all
  • perands and operators first
  • 4. Function references: The case of most interest!
  • Order of evaluation is crucial

Functional side effects - when a function changes a two-way parameter or a nonlocal variable

slide-5
SLIDE 5

CSCI325 Chapter 7 Dr Ahmed Rafea 5

Arithmetic Expressions

The problem with functional side effects:

  • When a function referenced in an expression

alters another operand of the expression e.g., for a parameter change:

a = 10; b = a + fun(&a); /* Assume that fun changes its parameter */

Two Possible Solutions to the Problem:

  • 1. Write the language definition to disallow

functional side effects

  • No two-way parameters in functions
  • No nonlocal references in functions
  • Advantage: it works!
  • Disadvantage: Programmers want the flexibility
  • f two-way parameters (what about C?) and

nonlocal references

  • 2. Write the language definition to demand that
  • perand evaluation order be fixed
  • Disadvantage: limits some compiler
  • ptimizations
slide-6
SLIDE 6

CSCI325 Chapter 7 Dr Ahmed Rafea 6

Conditional Expressions

  • C, C++, and Java (?:)

e.g. average = (count == 0)? 0 : sum / count;

slide-7
SLIDE 7

CSCI325 Chapter 7 Dr Ahmed Rafea 7

Relational Expressions

  • Use relational operators and
  • perands of various types
  • Evaluate to some boolean

representation

  • Operator symbols used vary

somewhat among languages (!=, /=, .NE., <>, #)

slide-8
SLIDE 8

CSCI325 Chapter 7 Dr Ahmed Rafea 8

Boolean Expressions

Operands are boolean and the result is boolean

  • Operators:

FORTRAN 77 FORTRAN 90 C Ada .AND. and && and .OR. or || or .NOT. not ! not xor –

  • C has no boolean type--it uses int type

with 0 – for false and nonzero for true – –

  • One odd characteristic of C’s

expressions: – a < b < c is a legal expression, but the – result is not what you might expect

slide-9
SLIDE 9

CSCI325 Chapter 7 Dr Ahmed Rafea 9

Boolean Expressions

Short Circuit Evaluation Pascal: does not use short-circuit evaluation Problem: table look-up index := 1; while (index <= length) and (LIST[index] <> value) do index := index + 1 C, C++, and Java: use short-circuit evaluation for the usual Boolean operators (&& and ||), but also provide bitwise Boolean operators that are not short circuit (& and |) Ada: programmer can specify either (short-circuit is specified with and then and or else) FORTRAN 77: short circuit, but any side-affected place must be set to undefined Short-circuit evaluation exposes the potential problem of side effects in expressions e.g. (a > b) || (b++ / 3)

slide-10
SLIDE 10

CSCI325 Chapter 7 Dr Ahmed Rafea 10

Operator Overloading

  • Some is common (e.g., + for int and

float)

  • Some is potential trouble (e.g., * in C

and C++)

  • Can be avoided by introduction of new

symbols (e.g., Pascal’s div)

  • C++ and Ada allow user-defined
  • verloaded operators

Potential problems:

– Users can define nonsense operations – Readability may suffer

slide-11
SLIDE 11

CSCI325 Chapter 7 Dr Ahmed Rafea 11

Assignment Statements

The operator symbol:

  • 1. =

FORTRAN, BASIC, PL/I, C, C++, Java

  • 2. := ALGOLs, Pascal, Modula-2, Ada

= can be bad if it is overloaded for the

relational operator for equality e.g. (PL/I) A = B = C; Note difference from C More complicated assignments:

  • 1. Multiple targets (PL/I)

A, B = 10

  • 2. Conditional targets (C, C++, and Java)

(first = true) ? total : subtotal = 0

  • 3. Compound assignment operators (C, C++, and

Java) sum += next;

  • 4. Unary assignment operators (C, C++, and Java)

a++; C, C++, and Java treat = as an arithmetic binary

  • perator

e.g. a = b * (c = d * 2 + 1) + 1 This is inherited from ALGOL 68

slide-12
SLIDE 12

CSCI325 Chapter 7 Dr Ahmed Rafea 12

Assignment as an Expression

  • In C, C++, and Java, the assignment statement

produces a result

  • So, they can be used as operands in

expressions e.g.

while ((ch = getchar() != EOF) { ... }

Disadvantage

  • Another kind of expression side effect

Mixed-Mode Assignment

  • In FORTRAN, C, and C++, any numeric value can

be assigned to any numeric scalar variable; whatever conversion is necessary is done

  • In Pascal, integers can be assigned to reals, but

reals cannot be assigned to integers (the programmer must specify whether the conversion from real to integer is truncated or rounded)

  • In Java, only widening assignment coercions are

done

  • In Ada, there is no assignment coercion
slide-13
SLIDE 13

CSCI325 Chapter 7 Dr Ahmed Rafea 13

Control Structure

Levels of Control Flow:

  • 1. Within expressions
  • 2. Among program units
  • 3. Among program statements

Evolution:

  • FORTRAN I control statements were based

directly on IBM 704 hardware

  • Much research and argument in the1960s about

the issue

  • One important result: It was proven that all

flowcharts can be coded with only two-way selection and pretest logical loops Def: A control structure is a control statement and the statements whose execution it controls Overall Design Question: What control statements should a language have, beyond selection and pretest logical loops?

slide-14
SLIDE 14

CSCI325 Chapter 7 Dr Ahmed Rafea 14

Selection Statements

Design Issues:

  • 1. What is the form and type of the control

expression?

  • 2. What is the selectable segment form (single

statement, statement sequence, compound statement)?

  • 3. How should the meaning of nested selectors

be specified? Single-Way Examples FORTRAN IF: IF (boolean_expr) statement Problem: can select only a single statement; to s e l e c t m

  • r

e , a goto must be used, as in the following example

slide-15
SLIDE 15

CSCI325 Chapter 7 Dr Ahmed Rafea 15

Selection Statements

FORTRAN example:

IF (.NOT. condition) GOTO 20 ... ... 20 CONTINUE

ALGOL 60 if:

if (boolean_expr) then begin ... end

Two-way Selector Examples ALGOL 60 if:

if (boolean_expr) then statement (the then clause) else statement (the else clause)

  • The statements could be single or compound
slide-16
SLIDE 16

CSCI325 Chapter 7 Dr Ahmed Rafea 16

Selection Statements

Nested Selectors e.g. (Pascal)

if ... then if ... then ... else ...

Which then gets the else? Pascal's rule: else goes with the nearest then ALGOL 60's solution - disallow direct nesting

if ... then if ... then begin begin if ... if ... then ... then ... end else ... else ... end

slide-17
SLIDE 17

CSCI325 Chapter 7 Dr Ahmed Rafea 17

Selection Statements

FORTRAN 77, Ada, Modula-2 solution - closing special words e.g. (Ada)

if ... then if ... then if ... then if ... then ... ... else end if ... else end if ... end if end if

Advantage: flexibility and readability Modula-2 uses the same closing special word for for all control structures (END)

  • This results in poor readability
slide-18
SLIDE 18

CSCI325 Chapter 7 Dr Ahmed Rafea 18

Multiple Selection Constructs

Design Issues:

  • 1. What is the form and type of the control

expression?

  • 2. What segments are selectable (single,

compound, sequential)?

  • 3. Is the entire construct encapsulated?
  • 4. Is execution flow through the structure restricted

to include just a single selectable segment?

  • 5. What is done about unrepresented expression

values?

Early Multiple Selectors:

  • 1. FORTRAN arithmetic IF (a three-way selector)

IF (arithmetic expression) N1, N2, N3

Bad aspects:

  • Not encapsulated (selectable segments could

be anywhere)

  • Segments require GOTOs
  • 2. FORTRAN computed GOTO and assigned GOTO
slide-19
SLIDE 19

CSCI325 Chapter 7 Dr Ahmed Rafea 19

Multiple Selection Constructs

Modern Multiple Selectors

  • 1. Pascal case (from Hoare's contribution to

ALGOL W)

case expression of

constant_list_1 : statement_1; ... constant_list_n : statement_n

end

Design choices:

  • 1. Expression is any ordinal type

(int, boolean, char, enum)

  • 2. Segments can be single or compound
  • 3. Construct is encapsulated
  • 4. Only one segment can be executed per

execution of the construct

  • 5. In Wirth's Pascal, result of an unrepresented

control expression value is undefined (In 1984 ISO Standard, it is a runtime error)

  • Many dialects now have otherwise or else

clause

slide-20
SLIDE 20

CSCI325 Chapter 7 Dr Ahmed Rafea 20

Multiple Selection Constructs

  • 2. The C and C++ switch

switch (expression) {

constant_expression_1 : statement_1; ... constant_expression_n : statement_n; [default: statement_n+1]

}

Design Choices: (for switch)

  • 1. Control expression can be only an integer type
  • 2. Selectable segments can be statement

sequences, blocks, or compound statements

  • 3. Construct is encapsulated
  • 4. Any number of segments can be executed in
  • ne execution of the construct (there is no

implicit branch at the end of selectable segments)

  • 5. default clause is for unrepresented values (if

there is no default, the whole statement does nothing)

  • Design choice 4 is a trade-off between

reliability and flexibility (convenience)

  • To avoid it, the programmer must supply a

break statement for each segment

slide-21
SLIDE 21

CSCI325 Chapter 7 Dr Ahmed Rafea 21

Multiple Selection Constructs

  • 3. Ada's case is similar to Pascal's case, except:
  • 1. Constant lists can include:
  • Subranges

e.g., 10..15

  • Boolean OR operators

e.g.,

1..5 | 7 | 15..20

  • 2. Lists of constants must be exhaustive
  • Often accomplished with others clause
  • This makes it more reliable

Multiple Selectors can appear as direct extensions to two-way selectors, using else-if clauses (ALGOL 68, FORTRAN 77, Modula-2, Ada) Ada:

if ... then ... elsif ... then ... elsif ... then ... else ... end if

  • Far more readable than deeply nested if's
  • Allows a boolean gate on every selectable group
slide-22
SLIDE 22

CSCI325 Chapter 7 Dr Ahmed Rafea 22

Iterative Statements

  • The repeated execution of a statement or

compound statement is accomplished either by iteration or recursion; here we look at iteration, because recursion is unit-level control General design Issues for iteration control statements:

  • 1. How is iteration controlled?
  • 2. Where is the control mechanism in the loop?
slide-23
SLIDE 23

CSCI325 Chapter 7 Dr Ahmed Rafea 23

Counter-Controlled Loops

Design Issues:

  • 1. What is the type and scope of the loop var?
  • 2. What is the value of the loop var at loop

termination?

  • 3. Should it be legal for the loop var or loop

parameters to be changed in the loop body, and if so, does the change affect loop control?

  • 4. Should the loop parameters be evaluated only
  • nce, or once for every iteration
slide-24
SLIDE 24

CSCI325 Chapter 7 Dr Ahmed Rafea 24

Counter-Controlled Loops

  • 1. FORTRAN 77 and 90
  • Syntax: DO label var = start, finish [, stepsize]
  • Stepsize can be any value but zero
  • Parameters can be expressions
  • Design choices:
  • 1. Loop var can be INTEGER, REAL, or DOUBLE
  • 2. Loop var always has its last value
  • 3. The loop var cannot be changed in the loop, but

the parameters can; because they are evaluated

  • nly once, it does not affect loop control
  • 4. Loop parameters are evaluated only once

FORTRAN 90’s Other DO

  • Syntax:

[name:] DO variable = initial, terminal [, stepsize] …

END DO [name]

  • Loop var must be an INTEGER
slide-25
SLIDE 25

CSCI325 Chapter 7 Dr Ahmed Rafea 25

Counter-Controlled Loops

  • 2. ALGOL 60
  • Syntax: for var := <list_of_stuff> do statement

where <list_of_stuff> can have:

  • list of expressions
  • expression step expression until expression
  • expression while boolean_expression

for index := 1 step 2 until 50, 60, 70, 80, index + 1 until 100 do (index = 1, 3, 5, 7, ..., 49, 60, 70, 80, 81, 82, ..., 100)

  • ALGOL 60 Design choices:
  • 1. Control expression can be int or real; its

scope is whatever it is declared to be

  • 2. Control var has its last assigned value after

loop termination

  • 3. The loop var cannot be changed in the loop,

but the parameters can, and when they are, it affects loop control

  • 4. Parameters are evaluated with every iteration,

making it very complex and difficult to read

slide-26
SLIDE 26

CSCI325 Chapter 7 Dr Ahmed Rafea 26

Counter-Controlled Loops

  • 3. Pascal
  • Syntax:

for variable := initial (to | downto) final do

statement

  • Design Choices:
  • 1. Loop var must be an ordinal type of usual scope
  • 2. After normal termination, loop var is undefined
  • 3. The loop var cannot be changed in the loop; the

loop parameters can be changed, but they are evaluated just once, so it does not affect loop control

  • 4. Just once
  • 4. Ada
  • Syntax:

for var in [reverse] discrete_range loop ... end loop

slide-27
SLIDE 27

CSCI325 Chapter 7 Dr Ahmed Rafea 27

Counter-Controlled Loops

Ada Design choices:

  • 1. Type of the loop var is that of the discrete range;

its scope is the loop body (it is implicitly declared)

  • 2. The loop var does not exist outside the loop
  • 3. The loop var cannot be changed in the loop,

but the discrete range can; it does not affect loop control

  • 4. The discrete range is evaluated just once
  • 5. C
  • Syntax:

for ([expr_1] ; [expr_2] ; [expr_3]) statement

  • The expressions can be whole statements, or even

statement sequences, with the statements separated by commas

  • The value of a multiple-statement expression is

the value of the last statement in the expression e.g.,

for (i = 0, j = 10; j == i; i++) ...

slide-28
SLIDE 28

CSCI325 Chapter 7 Dr Ahmed Rafea 28

Counter-Controlled Loops

  • If the second expression is absent, it is an infinite

loop C Design Choices:

  • 1. There is no explicit loop var
  • 2. Irrelevant
  • 3. Everything can be changed in the loop
  • 4. Pretest
  • 5. The first expression is evaluated once, but the
  • ther two are evaluated with each iteration
  • This loop statement is the most flexible
  • 6. C++
  • Differs from C in two ways:
  • 1. The control expression can also be Boolean
  • 2. The initial expression can include variable

definitions (scope is from the definition to the end of the function in which it is defined)

  • 7. Java
  • Differs from C++ in two ways:
  • 1. Control expression must be Boolean
  • 2. Scope of variables defined in the initial

expression is only the loop body

slide-29
SLIDE 29

CSCI325 Chapter 7 Dr Ahmed Rafea 29

Logically-Controlled Loops

Logically-Controlled Loops

  • Design Issues:
  • 1. Pretest or postest?
  • 2. Should this be a special case of the counting

loop statement (or a separate statement)?

  • Language Examples:
  • 1. Pascal has separate pretest and posttest

logical loop statements (while-do and

repeat-until)

  • 2. C and C++ also have both, but the control

expression for the posttest version is treated just like in the pretest case (while - do and

do - while)

3 Java is like C, except the control expression must be Boolean (and the body can only be entered at the beginning--Java has no goto)

  • 4. Ada has a pretest version, but no posttest
  • 5. FORTRAN 77 and 90 have neither
slide-30
SLIDE 30

CSCI325 Chapter 7 Dr Ahmed Rafea 30

User-Located Loop Control Mechanisms

  • Design issues:
  • 1. Should the conditional be part of the exit?
  • 2. Should the mechanism be allowed in an already

controlled loop?

  • 3. Should control be transferable out of more than
  • ne loop?

Examples:

  • 1. Ada - conditional or unconditional; for any loop;

any number of levels

for ... loop LOOP1: ... while ... loop exit when ... ... ... LOOP2: end loop for ... loop ... exit LOOP1 when .. ... end loop LOOP2; ... end loop LOOP1;

slide-31
SLIDE 31

CSCI325 Chapter 7 Dr Ahmed Rafea 31

User-Located Loop Control Mechanisms

  • 2. C , C++, and Java - break

Unconditional; for any loop or switch;

  • ne level only (Java’s can have a label)

There is also has a continue statement for loops; it skips the remainder of this iteration, but does not exit the loop

  • 3. FORTRAN 90 - EXIT

Unconditional; for any loop, any number of levels FORTRAN 90 also has CYCLE, which has the same semantics as C's continue

slide-32
SLIDE 32

CSCI325 Chapter 7 Dr Ahmed Rafea 32

Unconditional Branching

Problem: readability

  • Some languages do not have them:e.g., Modula-2

and Java Label forms:

  • 1. Unsigned int constants: Pascal (with colon)

FORTRAN (no colon)

  • 2. Identifiers with colons: ALGOL 60, C
  • 3. Identifiers in << ... >>: Ada
  • 4. Variables as labels: PL/I
  • Can be assigned values and passed as

parameters

  • Highly flexible, but make programs impossible

to read and difficult to implement

slide-33
SLIDE 33

CSCI325 Chapter 7 Dr Ahmed Rafea 33

Unconditional Branching

Restrictions on Pascal's gotos: A statement group is either a compound statement

  • r the body of a repeat-until

The target of a goto cannot be a statement in a statement group that is not active

  • Means the target can never be in a statement

group that is at the same level or is nested more deeply than the one with the goto

  • An important remaining problem: the target can

be in any enclosing subprogram scope, as long as the statement is not in a statement group

  • This means that a goto can terminate any

number of subprograms

slide-34
SLIDE 34

CSCI325 Chapter 7 Dr Ahmed Rafea 34

Guarded Commands

Purpose: to support a new programming methodology (verification during program development)

  • 1. Selection: if <boolean> -> <statement>

[] <boolean> -> <statement> ... [] <boolean> -> <statement>

fi

  • Semantics: when this construct is reached,
  • Evaluate all boolean expressions
  • If more than one are true, choose one

nondeterministically

  • If none are true, it is a runtime error

Idea: if the order of evaluation is not important, the program should not specify one See book examples (p. 319)!

slide-35
SLIDE 35

CSCI325 Chapter 7 Dr Ahmed Rafea 35

Guarded Commands

  • 2. Loops

do <boolean> -> <statement>

[] <boolean> -> <statement> ... [] <boolean> -> <statement>

  • d

Semantics: For each iteration:

  • Evaluate all boolean expressions
  • If more than one are true, choose one

nondeterministically; then start loop again

  • If none are true, exit loop

See book example (p. 320) Connection between control statements and program verification is intimate

  • Verification is impossible with gotos
  • Verification is possible with only selection and

logical pretest loops

  • Verification is relatively simple with only

guarded commands Chapter Conclusion: Choice of control statements beyond selection and logical pretest loops is a trade-off between language size and writability

slide-36
SLIDE 36

CSCI325 Chapter 7 Dr Ahmed Rafea 36

Exception Handling

In a language without exception handling: When an exception occurs, control goes to the

  • perating system, where a message is displayed

and the program is terminated In a language with exception handling: Programs are allowed to trap some exceptions, thereby providing the possibility of fixing the problem and continuing Many languages allow programs to trap input/

  • utput errors (including EOF)

Def: An exception is any unusual event, either erroneous or not, detectable by either hardware or software, that may require special processing Def: The special processing that may be required after the detection of an exception is called exception handling Def: The exception handling code unit is called an exception handler

slide-37
SLIDE 37

CSCI325 Chapter 7 Dr Ahmed Rafea 37

Exception Handling

Def: An exception is raised when its associated event occurs A language that does not have exception handling capabilities can still define, detect, raise, and handle exceptions

  • Alternatives:
  • 1. Send an auxiliary parameter or use the return

value to indicate the return status of a s u b p r

  • g

r a m

  • e.g., C standard library functions
  • 2. Pass a label parameter to all subprograms

(error return is to the passed label)

  • e.g., FORTRAN
  • 3. Pass an exception handling subprogram to all

subprograms Advantages of Built-in Exception Handling:

  • 1. Error detection code is tedious to write and it

clutters the program

  • 2. Exception propagation allows a high level of

reuse of exception handling code

slide-38
SLIDE 38

CSCI325 Chapter 7 Dr Ahmed Rafea 38

Exception Handling

Design Issues for Exception Handling:

  • 1. How and where are exception handlers specified

and what is their scope?

  • 2. How is an exception occurrence bound to an

exception handler?

  • 3. Where does execution continue, if at all, after an

exception handler completes its execution?

  • 4. How are user-defined exceptions specified?
  • 5. Should there be default exception handlers for

programs that do not provide their own?

  • 6. Can built-in exceptions be explicitly raised?
  • 7. Are hardware-detectable errors treated as

exceptions that can be handled?

  • 8. Are there any built-in exceptions?
  • 7. How can exceptions be disabled, if at all?
slide-39
SLIDE 39

CSCI325 Chapter 7 Dr Ahmed Rafea 39

Ada Exception Handling

Def: The frame of an exception handler in Ada is either a subprogram body, a package body, a task, or a block

  • Because exception handlers are usually local to

the code in which the exception can be raised, they do not have parameters

  • Handler form:

exception when exception_name {| exception_name} =>

statement_sequence

... when ... ...

[when others => statement_sequence ]

  • Handlers are placed at the end of the block or

unit in which they occur

slide-40
SLIDE 40

CSCI325 Chapter 7 Dr Ahmed Rafea 40

Ada Exception Handling

  • Binding Exceptions to Handlers
  • If the block or unit in which an exception is raised

does not have a handler for that exception, the exception is propagated elsewhere to be handled

  • 1. Procedures - propagate it to the caller
  • 2. Blocks - propagate it to the scope in which it
  • ccurs
  • 3. Package body - propagate it to the declaration

part of the unit that declared the package (if it is a library unit (no static parent), the program is terminated)

  • 4. Task - no propagation; if it has no handler,

execute it; in either case, mark it "completed"

  • Continuation
  • The block or unit that raises an exception but

does not handle it is always terminated (also any block or unit to which it is propagated that does not handle it)

slide-41
SLIDE 41

CSCI325 Chapter 7 Dr Ahmed Rafea 41

Ada Exception Handling

  • User-defined Exceptions:

exception_name_list : exception;

raise [exception_name]

(the exception name is not required if it is in a handler--in this case, it propagates the same exception)

  • Exception conditions can be disabled with:

pragma SUPPRESS(exception_list)

  • Predefined Exceptions:

CONSTRAINT_ERROR - index constraints, range

constraints, etc.

NUMERIC_ERROR - numeric operation cannot

return a correct value, etc.

slide-42
SLIDE 42

CSCI325 Chapter 7 Dr Ahmed Rafea 42

Ada Exception Handling

PROGRAM_ERROR - call to a subprogram whose

body has not been elaborated

STORAGE_ERROR - system runs out of heap TASKING_ERROR - an error associated with tasks

  • --> SHOW program (pp. 549-550)
  • Evaluation
  • The Ada design for exception handling

embodies the state-of-the-art in language design in 1980

  • A significant advance over PL/I
  • Ada was the only widely used language with

exception handling until it was added to C++

slide-43
SLIDE 43

CSCI325 Chapter 7 Dr Ahmed Rafea 43

C++ Exception Handling

  • Added to C++ in 1990
  • Design is based on that of CLU, Ada, and ML

Exception Handlers

  • Form:

try {

  • - code that is expected to raise an exception

} catch (formal parameter) {

  • - handler code

}

...

catch (formal parameter) {

  • - handler code

}

  • catch is the name of all handlers--it is an
  • verloaded name, so the formal parameter of

each must be unique

  • The formal parameter need not have a variable.

It can be simply a type name to distinguish the handler it is in from others

  • The formal parameter can be used to transfer

information to the handler

  • The formal parameter can be an ellipsis, in

which case it handles all exceptions not yet handled

slide-44
SLIDE 44

CSCI325 Chapter 7 Dr Ahmed Rafea 44

C++ Exception Handling

  • Binding Exceptions to Handlers
  • Exceptions are all raised explicitly by the

statement:

throw [expression];

  • The brackets are metasymbols
  • A throw without an operand can only appear in

a handler; when it appears, it simply reraises the exception, which is then handled elsewhere

  • The type of the expression disambiguates the

intended handler

  • Unhandled exceptions are propagated to the

caller of the function in which it is raised

  • This propagation continues to the main

function

  • If no handler is found, the program is

terminated

slide-45
SLIDE 45

CSCI325 Chapter 7 Dr Ahmed Rafea 45

C++ Exception Handling

  • Continuation
  • After a handler completes its execution, control

flows to the first statement after the last handler in the sequence of handlers of which it is an element

  • Other Design Choices
  • All exceptions are user-defined
  • Exceptions are neither specified nor declared
  • Functions can list the exceptions they may raise
  • Without a specification, a function can raise

any exception

  • Evaluation
  • It is odd that exceptions are not named and that

hardware- and system software-detectable exceptions cannot be handled

  • Binding exceptions to handlers through the type
  • f the parameter certainly does not promote

readability

slide-46
SLIDE 46

CSCI325 Chapter 7 Dr Ahmed Rafea 46

Java Exception Handling

  • Based on that of C++, but more in line with OOP

philosophy

  • All exceptions are objects of classes that are

descendants of the Throwable class

  • The Java library includes two subclasses of

Throwable :

  • 1. Error
  • Thrown by the Java interpreter for events

such as heap underflow

  • Never handled by user programs
  • 2. Exception
  • User-defined exceptions are usually

subclasses of this

  • Has two predefined subclasses, IOException

and RuntimeException (e.g.,

ArrayIndexOutOfBoundsException and NullPointerException

slide-47
SLIDE 47

CSCI325 Chapter 7 Dr Ahmed Rafea 47

Java Exception Handling

  • Java Exception Handlers
  • Like those of C++, except every catch requires a

named parameter and all parameters must be descendants of Throwable

  • Syntax of try clause is exactly that of C++
  • Exceptions are thrown with throw, as in C++,

but often the throw includes the new operator to create the object, as in:

throw new MyException();

  • Binding an exception to a handler is simpler in

Java than it is in C++

  • An exception is bound to the first handler with

a parameter is the same class as the thrown

  • bject or an ancestor of it
  • An exception can be handled and rethrown by

including a throw in the handler (a handler could also throw a different exception)

slide-48
SLIDE 48

CSCI325 Chapter 7 Dr Ahmed Rafea 48

Java Exception Handling

  • Continuation
  • If no handler is found in the try construct, the

search is continued in the nearest enclosing try construct, etc.

  • If no handler is found in the method, the

exception is propagated to the method’s caller

  • If no handler is found (all the way to main), the

program is terminated

  • To insure that all exceptions are caught, a

handler can be included in any try construct that catches all exceptions

  • Simply use an Exception class parameter
  • Of course, it must be the last in the try

construct

  • Other Design Choices
  • The Java throws clause is quite different from

the throw class of C++

slide-49
SLIDE 49

CSCI325 Chapter 7 Dr Ahmed Rafea 49

Java Exception Handling

  • Exceptions of class Error and RunTimeException

and all of their descendants are called unchecked exceptions

  • All other exceptions are called checked

exceptions

  • Checked exceptions that may be thrown by a

method must be either:

  • 1. Listed in the throws clause, or
  • 2. Handled in the method
  • A method cannot declare more exceptions in its

throws clause than the method it overrides

  • A method that calls a method that lists a

particular checked exception in its throws clause has three alternatives for dealing with that exception:

  • 1. Catch and handle the exception
  • 2. Catch the exception and throw an exception

that is listed in its own throws clause

  • 3. Declare it in its throws clause and do not

handle it

slide-50
SLIDE 50

CSCI325 Chapter 7 Dr Ahmed Rafea 50

Java Exception Handling

  • The finally Clause
  • Can appear at the end of a try construct
  • Form:

finally { ... }

  • Purpose: To specify code that is to be

executed, regardless of what happens in the try construct

  • A try construct with a finally clause can be

used outside exception handling

try { for (index = 0; index < 100; index++) { … if (…) { return; } //** end of if } //** end of try clause finally { … } //** end of try construct

slide-51
SLIDE 51

CSCI325 Chapter 7 Dr Ahmed Rafea 51

Java Exception Handling

  • Evaluation
  • The types of exceptions makes more sense

than in the case of C++

  • The throws clause is better than that of C++

(The throw clause in C++ says little to the programmer)

  • The finally clause is often useful
  • The Java interpreter throws a variety of

exceptions that can be handled by user programs