n_broberg at hotmail.com
Fri Oct 1 15:48:47 EDT 2004
Alastair Reid wrote:
> > 3. Can I define my own exception types?
>Sadly, no. There is only one 'exception type'.
>You can use dynamics and encode new kinds of exceptions as Strings
> but that isn't very satisfactory.
But not at all, allowing you to declare your own exception types is
*exactly* what using dynamic exceptions is all about. No need for String
encodings, we can do far better than that. =)
If I have my own type of exceptions, by making that type an instance of
Typeable I can use the functions 'throwDyn' and 'catchDyn' instead of the
normal 'throw' and 'catch'. That way I can declare exception handlers that
only exceptions of a particular type, and just re-raises any other.
I could for instance write
main = do ... a bunch of computations ...
`catchDyn` (\e :: MyExceptionType1 -> ... handle exceptions of
`catchDyn` (\e :: MyExceptionType2 -> ... handle exceptions of
`catch` (\e -> ... handle exceptions of the built-in Exceptions type
(Note that the type annotations on the patterns are not needed if the types
can be inferred properly from within the handler. Note also that the
Typeable constraint can be automatically derived by ghc with -fglasgow-exts,
so no difficulty there either)
Check the section about dynamic exceptions at
for more info.
> > 4. Can I write code that can catch and handle multiple different
> > exception types from a single block of code?
>You use standard Haskell pattern matching so, yes, you can catch multiple
>kinds of exceptions. They're not different types though.
But yes they are, see above. Or rather, they can be, or they can be
constructors of a common user-defined type, combining common pattern
matching with dynamic matching on types. =)
> > 5. Is there anything different about working with exceptions in monads?
>Use raiseIO instead of raise to raise exceptions.
The functions for raising exceptions are called 'throw' and 'throwIO' (and
'throwDyn'), not raise.
The new MSN 8: advanced junk mail protection and 2 months FREE*
More information about the Haskell-Cafe