4 module Control.Exception,
9 import Prelude hiding (catch)
11 import Control.Exception
13 catchIO :: IO a -> (IOException -> IO a) -> IO a
16 handleIO :: (IOException -> IO a) -> IO a -> IO a
17 handleIO = flip catchIO
19 tryIO :: IO a -> IO (Either IOException a)
22 -- | A monad that can catch exceptions. A minimal definition
23 -- requires a definition of 'gcatch'.
25 -- Implementations on top of 'IO' should implement 'gblock' and 'gunblock' to
26 -- eventually call the primitives 'Control.Exception.block' and
27 -- 'Control.Exception.unblock' respectively. These are used for
28 -- implementations that support asynchronous exceptions. The default
29 -- implementations of 'gbracket' and 'gfinally' use 'gblock' and 'gunblock'
30 -- thus rarely require overriding.
32 class Monad m => ExceptionMonad m where
34 -- | Generalised version of 'Control.Exception.catch', allowing an arbitrary
35 -- exception handling monad instead of just 'IO'.
36 gcatch :: Exception e => m a -> (e -> m a) -> m a
38 -- | Generalised version of 'Control.Exception.block', allowing an arbitrary
39 -- exception handling monad instead of just 'IO'.
42 -- | Generalised version of 'Control.Exception.unblock', allowing an
43 -- arbitrary exception handling monad instead of just 'IO'.
44 gunblock :: m a -> m a
46 -- | Generalised version of 'Control.Exception.bracket', allowing an arbitrary
47 -- exception handling monad instead of just 'IO'.
48 gbracket :: m a -> (a -> m b) -> (a -> m c) -> m c
50 -- | Generalised version of 'Control.Exception.finally', allowing an arbitrary
51 -- exception handling monad instead of just 'IO'.
52 gfinally :: m a -> m b -> m a
57 gbracket before after thing =
60 r <- gunblock (thing a) `gonException` after a
66 r <- gunblock a `gonException` sequel
70 instance ExceptionMonad IO where
75 gtry :: (ExceptionMonad m, Exception e) => m a -> m (Either e a)
76 gtry act = gcatch (act >>= \a -> return (Right a))
77 (\e -> return (Left e))
79 -- | Generalised version of 'Control.Exception.handle', allowing an arbitrary
80 -- exception handling monad instead of just 'IO'.
81 ghandle :: (ExceptionMonad m, Exception e) => (e -> m a) -> m a -> m a
84 -- | Always executes the first argument. If this throws an exception the
85 -- second argument is executed and the exception is raised again.
86 gonException :: (ExceptionMonad m) => m a -> m b -> m a
87 gonException ioA cleanup = ioA `gcatch` \e ->
89 throw (e :: SomeException)