Lecture #8
Programming Languages
MISHRA 95
---Slide 1---
Exception Mechanisms
---Slide 2---
Exception Handling Mechanism


---Slide 3---
Exception Handler
procedure SUB is
BAD_DATA_VALUE: exception;
--Other declarations
begin
--Statements for normal execution
exception
when BAD_DATA_VALUE => --handler1
when CONSTRAINT_ERROR => --handler2
when others =>
--handler for all other exceptions
end;
---Slide 4---
Exception Handler in C++
try clause.
<exception_name><exception_name>
C++:
try {
statement1;
statement2;
. . .
if BadCondition { throw ExceptionName };
}
catch ExceptionName { //Handle
} //End Exception.
---Slide 5---
Raising An Exception
Constraint_Error)
raise in Ada)BAD_DATA_VALUE
exception BadDenominator of int;
fun InnerDivide(a:int, b:int): real =
if b = 0 then raise BadDenominator(b)
else real(a)/real(b);
fun Divide(a, b) = InnerDivide(a, b)
handle
BadDenominator(b) =>
(print(b); "is bad denominator, 0 used" ; 0.0);
---Slide 6---
Propagating an Exception
When an exception is handled in a subprogram other than the subprogram in which it is raised, the exception is said to be propagated from its point of origin to the point of handling.
How does the system determine the handler?
---Slide 7---
After an Exception is Handled ...
Where should the control be transferred to?
Choices: Control should be returned to---
---Slide 8---
Implementation Details
Handling of an exception is different depending on its source.
Signals in C are handled with sigaction
function in Unix.
---Slide 9---
Language Specific Exceptions
goto).
return is used to return control to
the handler and raise exception in the caller again.
---Slide 10---
Language Defined Exceptions in Ada
NUMERIC_ERROR:
CONSTRAINT_ERROR:
PROGRAM_ERROR:
STORAGE_ERROR:
TASKING_ERROR:
---Slide 11---
Example from Ada
with I_O_PACKAGE;
procedure INVERT_MATRIX is
use I_O_PACKAGE;
SINGULAR: exception;
MATRIX_SIZE: INTEGER;
type MATRIX is array (INTEGER range <>, INTEGER range <>) of FLOAT;
procedure INVERT(M: in out MATRIX) is
DETERMINANT: FLOAT;
EPSILON : constant FLOAT := 1.0E-10;
begin
-- Compute the determinant(M)
if (abs DETERMINANT) < EPSILON then
raise SINGULAR;
end if;
-- Compute inverse(M)
end;
.
.
.
---Last Slide---
Example (Contd.)
procedure TREAT_ONE_MATRIX(SIZE: INTEGER) is
M: MATRIX (1 .. SIZE, 1 .. SIZE);
begin
OBTAIN(M); INVERT(M); PRINT(M);
exception
when SINGULAR => PUT("MATRIX IS SINGULAR");
when others => PUT("UNEXPECTED ERROR");
end;
SINGULAR,'' in which case the procedure INVERT is
abandoned and the exception is propagated to the caller
TREAT_ONE_MATRIX.
TREAT_ONE_MATRIX is then suspended and the handler
prints the error message. At this point the call is completed and the
control returns to the caller.
begin
for I in 1 .. 20 loop;
GET (MATRIX_SIZE);
TREAT_ONE_MATRIX (MATRIX_SIZE);
end loop;
end;
[End of Lecture #8]