问题
everyone, I'm trying to understand how exceptions work in ML, but I have strange error, and I can't figure out what is wrong:
exception Factorial
fun checked_factorial n =
if n < 0 then
raise Factorial
else n;
fun factorial_driver () =
checked_factorial(~4)
handle
Factorial => print "Out of range.";
what may be wrong? thanks in advance for any help.
回答1:
You need to make sure that factorial_driver
has a consistent type. The non-exceptional case returns int
, so ML infers the function to be of type unit -> int
, but the exceptional case (that is, the print
expression) returns unit
, not int
.
Generally, you basically need to return a value of the same type in all cases.
来源:https://stackoverflow.com/questions/4497243/handling-exceptions-in-ml