Exception: Difference between revisions
(Control.Monad.Error) |
(exception implementation for non-monadic functions) |
||
Line 7: | Line 7: | ||
In general you should be very careful, not to mix up exceptions with [[error]]s. | In general you should be very careful, not to mix up exceptions with [[error]]s. | ||
Actually, an unhandled exception is an [[error]]. | Actually, an unhandled exception is an [[error]]. | ||
== Implementation == | |||
The great thing about Haskell is, that it is not necessary to hard-wire the exception handling into the language. | |||
Everything is already there to implement definition and handling of exceptions nicely. | |||
See the implementation in <hask>Control.Monad.Error</hask> (and please, excuse the misleading name, for now). | |||
<haskell> | |||
data MonadException e a = | |||
Success a | |||
| Exception e | |||
instance Monad (MonadException e) where | |||
return = Success | |||
Exception l >>= _ = Exception l | |||
Successt r >>= k = k r | |||
throw :: e -> MonadException e a | |||
throw = Exception | |||
catch :: MonadException e a -> (e -> MonadException e a) -> MonadException e a | |||
catch (Exception l) h = h l | |||
catch (Success r) _ = Success r | |||
</haskell> | |||
<!-- | |||
bracket :: MonadException e h -> (h -> MonadException e ()) -> (h -> MonadException e a) -> MonadException e a | |||
bracket open close body = | |||
do h <- open | |||
catch | |||
--> | |||
== See also == | == See also == |
Revision as of 14:12, 23 January 2008
An exception denotes an unpredictable situation at runtime, like "out of disk storage", "read protected file", "user removed disk while reading", "syntax error in user input".
These are situation which occur relatively seldom and thus their immediate handling would clutter the code which should describe the regular processing.
Since exceptions must be expected at runtime there are also mechanisms for (selectively) handling them.
(Control.Exception,try
, Control.Exception.catch
)
Unfortunately Haskell's standard library names common exceptions of IO actions IOError
and the module Control.Monad.Error
is about exception handling not error handling.
In general you should be very careful, not to mix up exceptions with errors.
Actually, an unhandled exception is an error.
Implementation
The great thing about Haskell is, that it is not necessary to hard-wire the exception handling into the language.
Everything is already there to implement definition and handling of exceptions nicely.
See the implementation in Control.Monad.Error
(and please, excuse the misleading name, for now).
data MonadException e a =
Success a
| Exception e
instance Monad (MonadException e) where
return = Success
Exception l >>= _ = Exception l
Successt r >>= k = k r
throw :: e -> MonadException e a
throw = Exception
catch :: MonadException e a -> (e -> MonadException e a) -> MonadException e a
catch (Exception l) h = h l
catch (Success r) _ = Success r