ML exceptions


(* exceptions with no type *)
exception DivideByZero;;

let divide x y = if y == 0 then raise DivideByZero else x / y;;

(* handling, or catching an exception *)
(* the type returned by the handler must be the same as the type 
of the expression "divide 5 0" *)
try divide 5 0 with DivideByZero -> (print_string "division by zero"; 0);;

exception EndOfList;;

let rec getI y i = match y with 
[] -> raise EndOfList;
| x :: xs -> if i = 0 then x else getI xs (i - 1);;

getI [6; 7] 1;;

getI [6; 7] 2;;

(* exceptions returning a type *)
exception NegativeIndex of int;;

let rec getI y i = 
if i < 0 then raise (NegativeIndex(i)) else
match y with 
[] -> raise EndOfList;
| x :: xs -> if i = 0 then x else getI xs (i - 1);;

let try_get x i = try getI x i with
  EndOfList -> (print_string "you need a longer list"; 0)
 |NegativeIndex(i) -> (print_string "you passed a negative index"; print_int i; 0);;

try_get [1; 3] 2;;

try_get [1; 3] (-2);;

(*instead of returning a dummy value, we may re-raise the exception *)
let try_get x i = try getI x i with
  EndOfList -> (print_string "you need a longer list"; raise EndOfList)
 |NegativeIndex(i) -> (print_string "you passed a negative index"; 
	print_int i; raise (NegativeIndex(i)));;

try_get [1; 3] 2;;

try_get [1; 3] (-2);;

Exceptions scope


let x = 6;;
let f y = x;;
let g h = let x = 2 in h(x + 1);;
let x = 4 in g(f);;


exception X;;

try 
(let f y = raise X in
	let g h = try h(1) with X -> 2
	in try g(f) with X -> 4 
) with X -> 6;;

ML exceptions: lab assignment

  1. Write a function that compares two lists for equality of elements and raises two different exceptions: one when the first list is shorter, and the other when the second one is shorter. Write a function that catches the exception, prints both lists indicating which one is shorter, and raises the exception again.
  2. Write a function that takes a tree and a list of symbols "l" and "r" and returns an element in the tree at the path given by teh sequence. An empty list indicates the root element. Define and raise an exception for the cases when the list is not well-formed (i.e. has invalid symbols), print the invalid symbol. Define and raise a different exception that indicates an invalid path in the tree. Return the node value and the symbol for the non-existing path, print them when handling the exception.

CSci 4651 course.