Can I pass an exception as a parameter in an sml function?
If so, would it be something like this?
foo(exc: exception) =
...
Yes, you can, but the type is exn, not exception:
- exception E;
exception E
- E;
val it = E(-) : exn
- exception Q;
exception Q
- fun f x e = if x > 0 then x else raise e;
val f = fn : int -> exn -> int
- f 1 E;
val it = 1 : int
- (f 0 E) handle E => 23 | Q => 49;
val it = 23 : int
- (f 0 Q) handle E => 23 | Q => 49;
val it = 49 : int
But whether it's useful for anything is a different matter.
Yes, you can. The type is exn. Here's an example of where it could be useful:
Say you've got a function that you don't know if terminates or not, and you want to handle this by wrapping it in a function that spawns a thread, calls the function in the thread, sets a timeout and, if the function hasn't returned within the timeout, kills the thread and throws a timeout exception passed in as argument.
The pseudocode could look like:
fun with_timeout t e f =
let val f' = ...run f inside thread...
...wait t time for thread to join...
...otherwise, kill thread and raise e...
in f' end
This function would have the type time -> exn -> ('a -> 'b) -> ('a -> 'b).
You could then write
fun with_timeout_option t f =
let exception Timeout
in SOME (with_timeout t Timeout f)
handle Timeout => NONE
end
and know that this particular Timeout exception can only be handled inside with_timeout_option, because this is the only place that allows pattern matching on it. So if f throws something, it can't be Timeout (it can be another exception called Timeout that shadows this one, or another exception entirely).
Another use-case where passing around exceptions might be useful would be if Standard ML supported pattern matching against an exception that was passed down, but it doesn't. If you have a passed-down exception e, then handle e => ... will interpret e as a variable exception rather than unify the caught exception with the one in your variable. Alas, you always have to handle exceptions statically in the scope they're made available, which is probably a good thing anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With