Exception 4
Exception 4
Exceptions
R. Sekar
1 / 15
Topics
2 / 15
3 / 15
Explicit Vs Implicit Control Transfer
Examples:
Function Pointers
Return Statements
Exceptions
4 / 15
Terminology
5 / 15
Terminology (Continued)
Resumption model: After the execution of the handler, control returns back to the
statement that raised the exception.
Example: signal handling in UNIX/C.
Termination Model: Control does not return to that statement after the handler is
executed.
Example: Exception handling in most programming languages (C++, Java and
OCAML).
6 / 15
Exception Handling in OCAML
Exceptions are like datatypes in many ways.
exception BadN;;
They may take arguments, such as:
exception BadM of string * int * int * int;;
Once defined, they may be raised in functions as follows:
# let rec comb(n, m) = if n<0 then raise BadN
else if m<0 then raise (BadM("M less than zero", 0, n, m))
else if m>n then raise (BadM("M > N", 1, n, m))
else if (m=0) || (m=n) then 1
else comb(n-1,m) + comb(n-1,m-1);;
val comb : int * int -> int = <fun>
# comb(-1, 2);;
Exception: BadN.
# comb(9, -1);;
Exception: BadM ("M less than zero", 0, 9, -1). 7 / 15
9 / 15
Exception Handling in OCAML (Continued)
The semantics of matching exception handlers is exactly as with function definitions.
In particular, when there are multiple matches, the first match is taken.
Example:
# let f n m =
try comb(n, m) with
BadN -> 1
| BadM(s, 0, x, y) -> (print_string "BadM exception, "; print_string (s^", ");
print_string "raised, ignoring\n"; 1);;
val f : int -> int -> int = <fun>
# f 2 (-1);;
BadM exception, M less than zero, raised, ignoring
- : int = 1
# f (-2) 1;;
- : int = 1
# f 1 3;;
Exception: BadM ("M > N", 1, 1, 3).
10 / 15
The syntactic constructs for exceptions parallel those of OCAML, and semantics of
exceptions remains essentially the same.
Syntax:
<blockWithHandler> ::= try <block> <match>
<match> ::= <handler> ... <handler>
<handler> ::= catch (<parameter decl>) { <block> }
11 / 15
use of g(-1) will print “negative value invalid”, g(16) will print “n too large”
If an unexpected error were to arise in evaluation of fac or g, such as running out of
memory, then “unknown exception” will be printed
12 / 15
Exception Vs Return Codes
Exceptions are often used to communucate error values from a callee to its caller.
Return values provide alternate means of communicating errors.
Example use of exception handler:
float g (int a, int b, int c) {
float x = fac(a) + fac(b) + fac(c) ; return x ; }
main() {
try { g(-1, 3, 25); }
catch (char *s) { cout << "Exception `" << s << "'raised, exiting\n"; }
catch (...) { cout << "Unknown exception, eixting\n";
}
We do not need to concern ourselves with every point in the program where an error
may arise.
13 / 15
15 / 15