| Copyright | (C) Edward Kmett 2013-2015 (c) Google Inc. 2012 |
|---|---|
| License | BSD-style (see the file LICENSE) |
| Maintainer | Edward Kmett <ekmett@gmail.com> |
| Stability | experimental |
| Portability | non-portable |
| Safe Haskell | Trustworthy |
| Language | Haskell98 |
Control.Monad.Catch
Description
This module supports monads that can throw extensible exceptions. The
exceptions are the very same from Control.Exception, and the operations
offered very similar, but here they are not limited to IO.
This code is in the style of both transformers and mtl, and is compatible with them, though doesn't mimic the module structure or offer the complete range of features in those packages.
This is very similar to ErrorT and MonadError, but based on features of
Control.Exception. In particular, it handles the complex case of
asynchronous exceptions by including mask in the typeclass. Note that the
extensible exceptions feature relies on the RankNTypes language extension.
- class Monad m => MonadThrow m where
- class MonadThrow m => MonadCatch m where
- class MonadCatch m => MonadMask m where
- mask_ :: MonadMask m => m a -> m a
- uninterruptibleMask_ :: MonadMask m => m a -> m a
- catchAll :: MonadCatch m => m a -> (SomeException -> m a) -> m a
- catchIOError :: MonadCatch m => m a -> (IOError -> m a) -> m a
- catchJust :: (MonadCatch m, Exception e) => (e -> Maybe b) -> m a -> (b -> m a) -> m a
- catchIf :: (MonadCatch m, Exception e) => (e -> Bool) -> m a -> (e -> m a) -> m a
- data Handler m a = Exception e => Handler (e -> m a)
- catches :: (Foldable f, MonadCatch m) => m a -> f (Handler m a) -> m a
- handle :: (MonadCatch m, Exception e) => (e -> m a) -> m a -> m a
- handleAll :: MonadCatch m => (SomeException -> m a) -> m a -> m a
- handleIOError :: MonadCatch m => (IOError -> m a) -> m a -> m a
- handleJust :: (MonadCatch m, Exception e) => (e -> Maybe b) -> (b -> m a) -> m a -> m a
- handleIf :: (MonadCatch m, Exception e) => (e -> Bool) -> (e -> m a) -> m a -> m a
- try :: (MonadCatch m, Exception e) => m a -> m (Either e a)
- tryJust :: (MonadCatch m, Exception e) => (e -> Maybe b) -> m a -> m (Either b a)
- onException :: MonadCatch m => m a -> m b -> m a
- bracket :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c
- bracket_ :: MonadMask m => m a -> m b -> m c -> m c
- finally :: MonadMask m => m a -> m b -> m a
- bracketOnError :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c
- class (Typeable * e, Show e) => Exception e where
- data SomeException :: * where
Typeclass
The mtl style typeclass
class Monad m => MonadThrow m where Source #
A class for monads in which exceptions may be thrown.
Instances should obey the following law:
throwM e >> x = throwM e
In other words, throwing an exception short-circuits the rest of the monadic computation.
Minimal complete definition
Methods
throwM :: Exception e => e -> m a Source #
Throw an exception. Note that this throws when this action is run in
the monad m, not when it is applied. It is a generalization of
Control.Exception's throwIO.
Should satisfy the law:
throwM e >> f = throwM e
Instances
class MonadThrow m => MonadCatch m where Source #
A class for monads which allow exceptions to be caught, in particular
exceptions which were thrown by throwM.
Instances should obey the following law:
catch (throwM e) f = f e
Note that the ability to catch an exception does not guarantee that we can
deal with all possible exit points from a computation. Some monads, such as
continuation-based stacks, allow for more than just a success/failure
strategy, and therefore catch cannot be used by those monads to properly
implement a function such as finally. For more information, see
MonadMask.
Minimal complete definition
Methods
catch :: Exception e => m a -> (e -> m a) -> m a Source #
Provide a handler for exceptions thrown during execution of the first
action. Note that type of the type of the argument to the handler will
constrain which exceptions are caught. See Control.Exception's
catch.
Instances
| MonadCatch IO Source # | |
| MonadCatch STM Source # | |
| (~) * e SomeException => MonadCatch (Either e) Source # | Since: 0.8.3 |
| MonadCatch m => MonadCatch (ListT m) Source # | |
| MonadCatch m => MonadCatch (MaybeT m) Source # | Catches exceptions from the base monad. |
| Monad m => MonadCatch (CatchT m) Source # | |
| (Error e, MonadCatch m) => MonadCatch (ErrorT e m) Source # | Catches exceptions from the base monad. |
| MonadCatch m => MonadCatch (ExceptT e m) Source # | Catches exceptions from the base monad. |
| MonadCatch m => MonadCatch (StateT s m) Source # | |
| MonadCatch m => MonadCatch (StateT s m) Source # | |
| (MonadCatch m, Monoid w) => MonadCatch (WriterT w m) Source # | |
| (MonadCatch m, Monoid w) => MonadCatch (WriterT w m) Source # | |
| MonadCatch m => MonadCatch (IdentityT * m) Source # | |
| MonadCatch m => MonadCatch (ReaderT * r m) Source # | |
| (MonadCatch m, Monoid w) => MonadCatch (RWST r w s m) Source # | |
| (MonadCatch m, Monoid w) => MonadCatch (RWST r w s m) Source # | |
class MonadCatch m => MonadMask m where Source #
A class for monads which provide for the ability to account for all possible exit points from a computation, and to mask asynchronous exceptions. Continuation-based monads are invalid instances of this class.
Note that this package does provide a MonadMask instance for CatchT.
This instance is only valid if the base monad provides no ability to
provide multiple exit. For example, IO or Either would be invalid base
monads, but Reader or State would be acceptable.
Instances should ensure that, in the following code:
f `finally` g
The action g is called regardless of what occurs within f, including
async exceptions.
Minimal complete definition
Methods
mask :: ((forall a. m a -> m a) -> m b) -> m b Source #
Runs an action with asynchronous exceptions disabled. The action is
provided a method for restoring the async. environment to what it was
at the mask call. See Control.Exception's mask.
uninterruptibleMask :: ((forall a. m a -> m a) -> m b) -> m b Source #
Like mask, but the masked computation is not interruptible (see
Control.Exception's uninterruptibleMask. WARNING:
Only use if you need to mask exceptions around an interruptible operation
AND you can guarantee the interruptible operation will only block for a
short period of time. Otherwise you render the program/thread unresponsive
and/or unkillable.
Arguments
| :: m a | acquire some resource |
| -> (a -> m ignored1) | release, no exception thrown |
| -> (a -> SomeException -> m ignored2) | release, some exception thrown; the exception will be rethrown |
| -> (a -> m b) | inner action to perform with the resource |
| -> m b |
A generalized version of the standard bracket function which allows distinguishing different exit cases. Instead of providing it a single release action, this function takes two different actions: one for the case of a successful run of the inner function, and one in the case of an exception. The former function is provided the acquired value, while the exception release function is provided both the acquired value and the exception that was thrown. The result values of both of these functions are ignored.
NOTE This method was added in version 0.9.0 of this
library. Previously, implementation of functions like bracket
and finally in this module were based on the mask and
uninterruptibleMask functions only, disallowing some classes of
tranformers from having MonadMask instances (notably
multi-exit-point transformers like ExceptT). If you are a
library author, you'll now need to provide an implementation for
this method. As two examples, here is a ReaderT implementation:
generalBracket acquire release cleanup use = ReaderT $ r ->
generalBracket
(runReaderT acquire r)
(resource -> runReaderT (release resource) r)
(resource e -> runReaderT (cleanup resource e) r)
(resource -> runReaderT (use resource) r)
This implementation reuses the base monad's generalBracket, and
simply uses the ReaderT environment to run the relevant
acquire, release, cleanup (for exceptions), and use
actions. A more complicated example is the implementation for
ExceptT, which must implement ExceptT's short-circuit logic
itself:
generalBracket acquire release cleanup use = ExceptT $
generalBracket
(runExceptT acquire)
(eresource ->
case eresource of
Left _ -> return ()
Right resource -> runExceptT (release resource) >> return ())
(eresource e ->
case eresource of
Left _ -> return ()
Right resource -> runExceptT (cleanup resource e) >> return ())
(either (return . Left) (runExceptT . use))
In this implementation, we need to deal with the potential that
the acquire action returned a Left (as opposed to succeeding
with a Right or throwing an exception via throwM), and
therefore have to handle the Left case explicitly when provide
release, cleanup, and use actions to the base monad's
implementation of generalBracket.
You should ensure that in all cases of the acquire action
completing successfully, either the release or cleanup
actions are called, regardless of what occurs in use.
Since: 0.9.0
Instances
| MonadMask IO Source # | |
| (~) * e SomeException => MonadMask (Either e) Source # | Since: 0.8.3 |
| Monad m => MonadMask (CatchT m) Source # | Note: This instance is only valid if the underlying monad has a single exit point! |
| (Error e, MonadMask m) => MonadMask (ErrorT e m) Source # | |
| MonadMask m => MonadMask (ExceptT e m) Source # | |
| MonadMask m => MonadMask (StateT s m) Source # | |
| MonadMask m => MonadMask (StateT s m) Source # | |
| (MonadMask m, Monoid w) => MonadMask (WriterT w m) Source # | |
| (MonadMask m, Monoid w) => MonadMask (WriterT w m) Source # | |
| MonadMask m => MonadMask (IdentityT * m) Source # | |
| MonadMask m => MonadMask (ReaderT * r m) Source # | |
| (MonadMask m, Monoid w) => MonadMask (RWST r w s m) Source # | |
| (MonadMask m, Monoid w) => MonadMask (RWST r w s m) Source # | |
Utilities
These functions follow those from Control.Exception, except that they are
based on methods from the MonadCatch typeclass. See
Control.Exception for API usage.
mask_ :: MonadMask m => m a -> m a Source #
Like mask, but does not pass a restore action to the argument.
uninterruptibleMask_ :: MonadMask m => m a -> m a Source #
Like uninterruptibleMask, but does not pass a restore action to the
argument.
catchAll :: MonadCatch m => m a -> (SomeException -> m a) -> m a Source #
Catches all exceptions, and somewhat defeats the purpose of the extensible exception system. Use sparingly.
catchIOError :: MonadCatch m => m a -> (IOError -> m a) -> m a Source #
Catch all IOError (eqv. IOException) exceptions. Still somewhat too
general, but better than using catchAll. See catchIf for an easy way
of catching specific IOErrors based on the predicates in System.IO.Error.
catchJust :: (MonadCatch m, Exception e) => (e -> Maybe b) -> m a -> (b -> m a) -> m a Source #
A more generalized way of determining which exceptions to catch at run time.
catchIf :: (MonadCatch m, Exception e) => (e -> Bool) -> m a -> (e -> m a) -> m a Source #
Catch exceptions only if they pass some predicate. Often useful with the
predicates for testing IOError values in System.IO.Error.
Generalized version of Handler
catches :: (Foldable f, MonadCatch m) => m a -> f (Handler m a) -> m a Source #
Catches different sorts of exceptions. See Control.Exception's catches
handle :: (MonadCatch m, Exception e) => (e -> m a) -> m a -> m a Source #
Flipped catch. See Control.Exception's handle.
handleAll :: MonadCatch m => (SomeException -> m a) -> m a -> m a Source #
Flipped catchAll
handleIOError :: MonadCatch m => (IOError -> m a) -> m a -> m a Source #
Flipped catchIOError
handleJust :: (MonadCatch m, Exception e) => (e -> Maybe b) -> (b -> m a) -> m a -> m a Source #
Flipped catchJust. See Control.Exception's handleJust.
handleIf :: (MonadCatch m, Exception e) => (e -> Bool) -> (e -> m a) -> m a -> m a Source #
Flipped catchIf
try :: (MonadCatch m, Exception e) => m a -> m (Either e a) Source #
Similar to catch, but returns an Either result. See Control.Exception's
try.
tryJust :: (MonadCatch m, Exception e) => (e -> Maybe b) -> m a -> m (Either b a) Source #
A variant of try that takes an exception predicate to select
which exceptions are caught. See Control.Exception's tryJust
onException :: MonadCatch m => m a -> m b -> m a Source #
Run an action only if an exception is thrown in the main action. The exception is not caught, simply rethrown.
bracket :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c Source #
Generalized abstracted pattern of safe resource acquisition and release
in the face of exceptions. The first action "acquires" some value, which
is "released" by the second action at the end. The third action "uses"
the value and its result is the result of the bracket.
If an exception occurs during the use, the release still happens before the exception is rethrown.
Note that this is essentially a type-specialized version of
generalBracket. This function has a more common signature (matching the
signature from Control.Exception), and is often more convenient to use. By
contrast, generalBracket is more expressive, allowing us to implement
other functions like bracketOnError.
bracket_ :: MonadMask m => m a -> m b -> m c -> m c Source #
Version of bracket without any value being passed to the second and
third actions.
finally :: MonadMask m => m a -> m b -> m a Source #
Perform an action with a finalizer action that is run, even if an exception occurs.
bracketOnError :: MonadMask m => m a -> (a -> m b) -> (a -> m c) -> m c Source #
Like bracket, but only performs the final action if there was an
exception raised by the in-between computation.
Re-exports from Control.Exception
class (Typeable * e, Show e) => Exception e where #
Any type that you wish to throw or catch as an exception must be an
instance of the Exception class. The simplest case is a new exception
type directly below the root:
data MyException = ThisException | ThatException
deriving Show
instance Exception MyExceptionThe default method definitions in the Exception class do what we need
in this case. You can now throw and catch ThisException and
ThatException as exceptions:
*Main> throw ThisException `catch` \e -> putStrLn ("Caught " ++ show (e :: MyException))
Caught ThisException
In more complicated examples, you may wish to define a whole hierarchy of exceptions:
---------------------------------------------------------------------
-- Make the root exception type for all the exceptions in a compiler
data SomeCompilerException = forall e . Exception e => SomeCompilerException e
instance Show SomeCompilerException where
show (SomeCompilerException e) = show e
instance Exception SomeCompilerException
compilerExceptionToException :: Exception e => e -> SomeException
compilerExceptionToException = toException . SomeCompilerException
compilerExceptionFromException :: Exception e => SomeException -> Maybe e
compilerExceptionFromException x = do
SomeCompilerException a <- fromException x
cast a
---------------------------------------------------------------------
-- Make a subhierarchy for exceptions in the frontend of the compiler
data SomeFrontendException = forall e . Exception e => SomeFrontendException e
instance Show SomeFrontendException where
show (SomeFrontendException e) = show e
instance Exception SomeFrontendException where
toException = compilerExceptionToException
fromException = compilerExceptionFromException
frontendExceptionToException :: Exception e => e -> SomeException
frontendExceptionToException = toException . SomeFrontendException
frontendExceptionFromException :: Exception e => SomeException -> Maybe e
frontendExceptionFromException x = do
SomeFrontendException a <- fromException x
cast a
---------------------------------------------------------------------
-- Make an exception type for a particular frontend compiler exception
data MismatchedParentheses = MismatchedParentheses
deriving Show
instance Exception MismatchedParentheses where
toException = frontendExceptionToException
fromException = frontendExceptionFromExceptionWe can now catch a MismatchedParentheses exception as
MismatchedParentheses, SomeFrontendException or
SomeCompilerException, but not other types, e.g. IOException:
*Main> throw MismatchedParenthesescatche -> putStrLn ("Caught " ++ show (e :: MismatchedParentheses)) Caught MismatchedParentheses *Main> throw MismatchedParenthesescatche -> putStrLn ("Caught " ++ show (e :: SomeFrontendException)) Caught MismatchedParentheses *Main> throw MismatchedParenthesescatche -> putStrLn ("Caught " ++ show (e :: SomeCompilerException)) Caught MismatchedParentheses *Main> throw MismatchedParenthesescatche -> putStrLn ("Caught " ++ show (e :: IOException)) *** Exception: MismatchedParentheses
Methods
toException :: e -> SomeException #
fromException :: SomeException -> Maybe e #
displayException :: e -> String #
Instances
| Exception BlockedIndefinitelyOnMVar | Since: 4.1.0.0 |
| Exception BlockedIndefinitelyOnSTM | Since: 4.1.0.0 |
| Exception Deadlock | Since: 4.1.0.0 |
| Exception AllocationLimitExceeded | Since: 4.8.0.0 |
| Exception CompactionFailed | Since: 4.10.0.0 |
| Exception AssertionFailed | Since: 4.1.0.0 |
| Exception SomeAsyncException | Since: 4.7.0.0 |
| Exception AsyncException | Since: 4.7.0.0 |
| Exception ArrayException | Since: 4.1.0.0 |
| Exception ExitCode | Since: 4.1.0.0 |
| Exception IOException | Since: 4.1.0.0 |
| Exception ErrorCall | Since: 4.0.0.0 |
| Exception ArithException | Since: 4.0.0.0 |
| Exception SomeException | Since: 3.0 |
data SomeException :: * where #
The SomeException type is the root of the exception type hierarchy.
When an exception of type e is thrown, behind the scenes it is
encapsulated in a SomeException.
Constructors
| SomeException :: SomeException |
Instances
| Show SomeException | Since: 3.0 |
| Exception SomeException | Since: 3.0 |