Catch an exception.
Some care must be taken. Remember that even though it is constrained
by the
Exception typeclass,
ε does
not stand
for "any" exception type; is has a concrete type when it gets to being
used in your code. Things are fairly straight-forward if you know
exactly the exception you are looking for:
catch
action
(\(e :: FirstWorldProblem) -> do
...
)
but more awkward when you don't.
If you just need to catch all exceptions, the pattern for that is as
follows:
catch
action
(\(e :: SomeException) -> do
...
)
The
SomeException type is the root type of all exceptions; or
rather, all types that have an instance of
Exception can be
converted into this root type. Thus you
can catch all
synchronous exceptions but you can't tell which type of exception it
was originally; you rely on the
Show instance (which is the
default that
displayException falls back to) to display a
message which will hopefully be of enough utility to figure out what
the problem is. In fairness it usually is. (This all seems a bit of a
deficiency in the underlying exception machinery but it's what we
have)
This
catch function will
not catch asynchonous
exceptions. If you need to do that, see the more comprehensive
exception handling facilities offered by
safe-exceptions, which
in turn builds on
exceptions and
base). Note that
Program implements
MonadCatch so you can use the full
power available there if required.