(* --------------------------------------------------------- *) (* -- Illustrating basic use of exceptions in ML. -- *) (* -- Author: Roni Khardon. Adopted by Alan G. Labouseur -- *) (* ----------------------------------------------------------*) (* Handling overflow - a pre-defined exception *) fun fac(0)=1 | fac(n) = n * fac(n-1) ; (* this raises an overflow exception for fac(33); *) fun silentfailfac(n) = fac(n) handle overflow => 0 ; silentfailfac(8); (* ok *) silentfailfac(33); (* Exception handled *) (* Find index of element in a list, if not in list we raise our own exception *) exception NotThere; fun getIndex(x, []) = raise NotThere | getIndex(x, h::t) = if x=h then 1 else 1 + getIndex(x,t); (* Here we wrap the previous function, giving a printed result. *) fun UgetIndex(x,L) = let val a= getIndex(x,L) in (print "The value is in position "; print(Int.toString(a)); print "\n") end handle NotThere => print("The element is not in the list\n") ; (* Test cases *) val a = [1,2,3,4,5,6,7,8,9]; val b = getIndex(1,a); val b = getIndex(5,a); (* val b = getIndex(15,a); *) val b = UgetIndex(1,a); val b = UgetIndex(5,a); val b = UgetIndex(15,a);