1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
5 -----------------------------------------------------------------------------
7 -- Module : Control.Exception
8 -- Copyright : (c) The University of Glasgow 2001
9 -- License : BSD-style (see the file libraries/base/LICENSE)
11 -- Maintainer : libraries@haskell.org
12 -- Stability : experimental
13 -- Portability : non-portable (extended exceptions)
15 -- This module provides support for raising and catching both built-in
16 -- and user-defined exceptions.
18 -- In addition to exceptions thrown by 'IO' operations, exceptions may
19 -- be thrown by pure code (imprecise exceptions) or by external events
20 -- (asynchronous exceptions), but may only be caught in the 'IO' monad.
21 -- For more details, see:
23 -- * /A semantics for imprecise exceptions/, by Simon Peyton Jones,
24 -- Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson,
27 -- * /Asynchronous exceptions in Haskell/, by Simon Marlow, Simon Peyton
28 -- Jones, Andy Moran and John Reppy, in /PLDI'01/.
30 -----------------------------------------------------------------------------
32 module Control.Exception (
34 -- * The Exception type
36 Exception(..), -- instance Eq, Ord, Show, Typeable
37 IOException, -- instance Eq, Ord, Show, Typeable
38 ArithException(..), -- instance Eq, Ord, Show, Typeable
39 ArrayException(..), -- instance Eq, Ord, Show, Typeable
41 AsyncException(..), -- instance Eq, Ord, Show, Typeable
43 #ifdef __GLASGOW_HASKELL__
44 NonTermination(..), nonTermination,
45 NestedAtomically(..), nestedAtomically,
48 BlockedOnDeadMVar(..),
49 BlockedIndefinitely(..),
58 -- * Throwing exceptions
59 throwIO, -- :: Exception -> IO a
60 throw, -- :: Exception -> a
61 ioError, -- :: IOError -> IO a
62 #ifdef __GLASGOW_HASKELL__
63 throwTo, -- :: ThreadId -> Exception -> a
66 -- * Catching Exceptions
68 -- |There are several functions for catching and examining
69 -- exceptions; all of them may only be used from within the
72 -- ** The @catch@ functions
73 catch, -- :: IO a -> (Exception -> IO a) -> IO a
74 #ifdef __GLASGOW_HASKELL__
76 catchJust, -- :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a
79 -- ** The @handle@ functions
80 handle, -- :: (Exception -> IO a) -> IO a -> IO a
81 handleJust,-- :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
83 -- ** The @try@ functions
84 try, -- :: IO a -> IO (Either Exception a)
85 tryJust, -- :: (Exception -> Maybe b) -> a -> IO (Either b a)
88 -- ** The @evaluate@ function
89 evaluate, -- :: a -> IO a
91 -- ** The @mapException@ function
92 mapException, -- :: (Exception -> Exception) -> a -> a
94 -- * Asynchronous Exceptions
98 -- ** Asynchronous exception control
100 -- |The following two functions allow a thread to control delivery of
101 -- asynchronous exceptions during a critical region.
103 block, -- :: IO a -> IO a
104 unblock, -- :: IO a -> IO a
105 blocked, -- :: IO Bool
107 -- *** Applying @block@ to an exception handler
111 -- *** Interruptible operations
117 assert, -- :: Bool -> a -> a
121 bracket, -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO ()
122 bracket_, -- :: IO a -> IO b -> IO c -> IO ()
125 finally, -- :: IO a -> IO b -> IO a
127 #ifdef __GLASGOW_HASKELL__
128 recSelError, recConError, irrefutPatError, runtimeError,
129 nonExhaustiveGuardsError, patError, noMethodBindingError,
134 #ifdef __GLASGOW_HASKELL__
139 import GHC.IOBase as ExceptionBase
140 import GHC.Exception hiding ( Exception )
145 import Hugs.Exception as ExceptionBase
153 import qualified System.IO.Error as H'98 (catch)
154 import System.IO.Error (ioError)
156 import DIOError -- defn of IOError type
157 import System (ExitCode())
158 import System.IO.Unsafe (unsafePerformIO)
159 import Unsafe.Coerce (unsafeCoerce)
161 -- minimum needed for nhc98 to pretend it has Exceptions
164 data Exception = IOException IOException
165 | ArithException ArithException
166 | ArrayException ArrayException
167 | AsyncException AsyncException
168 | ExitException ExitCode
171 class ({-Typeable e,-} Show e) => Exception e where
172 toException :: e -> SomeException
173 fromException :: SomeException -> Maybe e
175 data SomeException = forall e . Exception e => SomeException e
177 INSTANCE_TYPEABLE0(SomeException,someExceptionTc,"SomeException")
179 instance Show SomeException where
180 showsPrec p (SomeException e) = showsPrec p e
181 instance Exception SomeException where
185 type IOException = IOError
186 instance Exception IOError where
187 toException = SomeException
188 fromException (SomeException e) = Just (unsafeCoerce e)
190 instance Exception ExitCode where
191 toException = SomeException
192 fromException (SomeException e) = Just (unsafeCoerce e)
198 data PatternMatchFail
201 data BlockedOnDeadMVar
202 data BlockedIndefinitely
207 instance Show ArithException
208 instance Show ArrayException
209 instance Show AsyncException
210 instance Show AssertionFailed
211 instance Show PatternMatchFail
212 instance Show NoMethodError
213 instance Show Deadlock
214 instance Show BlockedOnDeadMVar
215 instance Show BlockedIndefinitely
216 instance Show ErrorCall
217 instance Show RecConError
218 instance Show RecSelError
219 instance Show RecUpdError
222 => IO a -- ^ The computation to run
223 -> (e -> IO a) -- ^ Handler to invoke if an exception is raised
225 catch io h = H'98.catch io (h . fromJust . fromException . toException)
227 throwIO :: Exception e => e -> IO a
228 throwIO = ioError . fromJust . fromException . toException
230 throw :: Exception e => e -> a
231 throw = unsafePerformIO . throwIO
233 evaluate :: a -> IO a
234 evaluate x = x `seq` return x
236 assert :: Bool -> a -> a
238 assert False _ = throw (toException (UserError "" "Assertion failed"))
242 #ifndef __GLASGOW_HASKELL__
243 -- Dummy definitions for implementations lacking asynchonous exceptions
245 block :: IO a -> IO a
247 unblock :: IO a -> IO a
250 blocked = return False
253 -----------------------------------------------------------------------------
254 -- Catching exceptions
256 -- |This is the simplest of the exception-catching functions. It
257 -- takes a single argument, runs it, and if an exception is raised
258 -- the \"handler\" is executed, with the value of the exception passed as an
259 -- argument. Otherwise, the result is returned as normal. For example:
261 -- > catch (openFile f ReadMode)
262 -- > (\e -> hPutStr stderr ("Couldn't open "++f++": " ++ show e))
264 -- For catching exceptions in pure (non-'IO') expressions, see the
265 -- function 'evaluate'.
267 -- Note that due to Haskell\'s unspecified evaluation order, an
268 -- expression may return one of several possible exceptions: consider
269 -- the expression @error \"urk\" + 1 \`div\` 0@. Does
270 -- 'catch' execute the handler passing
271 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
273 -- The answer is \"either\": 'catch' makes a
274 -- non-deterministic choice about which exception to catch. If you
275 -- call it again, you might get a different exception back. This is
276 -- ok, because 'catch' is an 'IO' computation.
278 -- Note that 'catch' catches all types of exceptions, and is generally
279 -- used for \"cleaning up\" before passing on the exception using
280 -- 'throwIO'. It is not good practice to discard the exception and
281 -- continue, without first checking the type of the exception (it
282 -- might be a 'ThreadKilled', for example). In this case it is usually better
283 -- to use 'catchJust' and select the kinds of exceptions to catch.
285 -- Also note that the "Prelude" also exports a function called
286 -- 'Prelude.catch' with a similar type to 'Control.Exception.catch',
287 -- except that the "Prelude" version only catches the IO and user
288 -- families of exceptions (as required by Haskell 98).
290 -- We recommend either hiding the "Prelude" version of 'Prelude.catch'
291 -- when importing "Control.Exception":
293 -- > import Prelude hiding (catch)
295 -- or importing "Control.Exception" qualified, to avoid name-clashes:
297 -- > import qualified Control.Exception as C
299 -- and then using @C.catch@
303 => IO a -- ^ The computation to run
304 -> (e -> IO a) -- ^ Handler to invoke if an exception is raised
306 catch = ExceptionBase.catchException
309 catches :: IO a -> [Handler a] -> IO a
310 catches io handlers = io `catch` catchesHandler handlers
312 catchesHandler :: [Handler a] -> SomeException -> IO a
313 catchesHandler handlers e = foldr tryHandler (throw e) handlers
314 where tryHandler (Handler handler) res
315 = case fromException e of
316 Just e' -> handler e'
319 data Handler a = forall e . Exception e => Handler (e -> IO a)
320 -- | The function 'catchJust' is like 'catch', but it takes an extra
321 -- argument which is an /exception predicate/, a function which
322 -- selects which type of exceptions we\'re interested in.
324 -- > result <- catchJust errorCalls thing_to_try handler
326 -- Any other exceptions which are not matched by the predicate
327 -- are re-raised, and may be caught by an enclosing
328 -- 'catch' or 'catchJust'.
331 => (e -> Maybe b) -- ^ Predicate to select exceptions
332 -> IO a -- ^ Computation to run
333 -> (b -> IO a) -- ^ Handler
335 catchJust p a handler = catch a handler'
336 where handler' e = case p e of
340 -- | A version of 'catch' with the arguments swapped around; useful in
341 -- situations where the code for the handler is shorter. For example:
343 -- > do handle (\e -> exitWith (ExitFailure 1)) $
345 handle :: Exception e => (e -> IO a) -> IO a -> IO a
348 -- | A version of 'catchJust' with the arguments swapped around (see
350 handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a
351 handleJust p = flip (catchJust p)
353 -----------------------------------------------------------------------------
356 -- | This function maps one exception into another as proposed in the
357 -- paper \"A semantics for imprecise exceptions\".
359 -- Notice that the usage of 'unsafePerformIO' is safe here.
361 mapException :: Exception e => (e -> e) -> a -> a
362 mapException f v = unsafePerformIO (catch (evaluate v)
365 -----------------------------------------------------------------------------
366 -- 'try' and variations.
368 -- | Similar to 'catch', but returns an 'Either' result which is
369 -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an
370 -- exception was raised and its value is @e@.
372 -- > try a = catch (Right `liftM` a) (return . Left)
374 -- Note: as with 'catch', it is only polite to use this variant if you intend
375 -- to re-throw the exception after performing whatever cleanup is needed.
376 -- Otherwise, 'tryJust' is generally considered to be better.
378 -- Also note that "System.IO.Error" also exports a function called
379 -- 'System.IO.Error.try' with a similar type to 'Control.Exception.try',
380 -- except that it catches only the IO and user families of exceptions
381 -- (as required by the Haskell 98 @IO@ module).
383 try :: Exception e => IO a -> IO (Either e a)
384 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
386 -- | A variant of 'try' that takes an exception predicate to select
387 -- which exceptions are caught (c.f. 'catchJust'). If the exception
388 -- does not match the predicate, it is re-thrown.
389 tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)
393 Right v -> return (Right v)
394 Left e -> case p e of
396 Just b -> return (Left b)
398 onException :: IO a -> IO b -> IO a
399 onException io what = io `catch` \e -> do what
400 throw (e :: SomeException)
402 -----------------------------------------------------------------------------
403 -- Some Useful Functions
405 -- | When you want to acquire a resource, do some work with it, and
406 -- then release the resource, it is a good idea to use 'bracket',
407 -- because 'bracket' will install the necessary exception handler to
408 -- release the resource in the event that an exception is raised
409 -- during the computation. If an exception is raised, then 'bracket' will
410 -- re-raise the exception (after performing the release).
412 -- A common example is opening a file:
415 -- > (openFile "filename" ReadMode)
417 -- > (\handle -> do { ... })
419 -- The arguments to 'bracket' are in this order so that we can partially apply
422 -- > withFile name mode = bracket (openFile name mode) hClose
426 :: IO a -- ^ computation to run first (\"acquire resource\")
427 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
428 -> (a -> IO c) -- ^ computation to run in-between
429 -> IO c -- returns the value from the in-between computation
430 bracket before after thing =
433 r <- unblock (thing a) `onException` after a
439 -- | A specialised variant of 'bracket' with just a computation to run
442 finally :: IO a -- ^ computation to run first
443 -> IO b -- ^ computation to run afterward (even if an exception
445 -> IO a -- returns the value from the first computation
448 r <- unblock a `onException` sequel
453 -- | A variant of 'bracket' where the return value from the first computation
455 bracket_ :: IO a -> IO b -> IO c -> IO c
456 bracket_ before after thing = bracket before (const after) (const thing)
458 -- | Like bracket, but only performs the final action if there was an
459 -- exception raised by the in-between computation.
461 :: IO a -- ^ computation to run first (\"acquire resource\")
462 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
463 -> (a -> IO c) -- ^ computation to run in-between
464 -> IO c -- returns the value from the in-between computation
465 bracketOnError before after thing =
468 unblock (thing a) `onException` after a
471 -- -----------------------------------------------------------------------------
472 -- Asynchronous exceptions
476 #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
477 external influences, and can be raised at any point during execution.
478 'StackOverflow' and 'HeapOverflow' are two examples of
479 system-generated asynchronous exceptions.
481 The primary source of asynchronous exceptions, however, is
484 > throwTo :: ThreadId -> Exception -> IO ()
486 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
487 running thread to raise an arbitrary exception in another thread. The
488 exception is therefore asynchronous with respect to the target thread,
489 which could be doing anything at the time it receives the exception.
490 Great care should be taken with asynchronous exceptions; it is all too
491 easy to introduce race conditions by the over zealous use of
496 There\'s an implied 'block' around every exception handler in a call
497 to one of the 'catch' family of functions. This is because that is
498 what you want most of the time - it eliminates a common race condition
499 in starting an exception handler, because there may be no exception
500 handler on the stack to handle another exception if one arrives
501 immediately. If asynchronous exceptions are blocked on entering the
502 handler, though, we have time to install a new exception handler
503 before being interrupted. If this weren\'t the default, one would have
504 to write something like
507 > catch (unblock (...))
511 If you need to unblock asynchronous exceptions again in the exception
512 handler, just use 'unblock' as normal.
514 Note that 'try' and friends /do not/ have a similar default, because
515 there is no exception handler in this case. If you want to use 'try'
516 in an asynchronous-exception-safe way, you will need to use
522 Some operations are /interruptible/, which means that they can receive
523 asynchronous exceptions even in the scope of a 'block'. Any function
524 which may itself block is defined as interruptible; this includes
525 'Control.Concurrent.MVar.takeMVar'
526 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
527 and most operations which perform
528 some I\/O with the outside world. The reason for having
529 interruptible operations is so that we can write things like
533 > catch (unblock (...))
537 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
539 combination could lead to deadlock, because the thread itself would be
540 blocked in a state where it can\'t receive any asynchronous exceptions.
541 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
542 safe in the knowledge that the thread can receive exceptions right up
543 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
544 Similar arguments apply for other interruptible operations like
545 'System.IO.openFile'.
548 #if !(__GLASGOW_HASKELL__ || __NHC__)
549 assert :: Bool -> a -> a
551 assert False _ = throw (AssertionFailed "")
555 recSelError, recConError, irrefutPatError, runtimeError,
556 nonExhaustiveGuardsError, patError, noMethodBindingError
557 :: Addr# -> a -- All take a UTF8-encoded C string
559 recSelError s = throw (RecSelError (unpackCStringUtf8# s)) -- No location info unfortunately
560 runtimeError s = error (unpackCStringUtf8# s) -- No location info unfortunately
562 nonExhaustiveGuardsError s = throw (PatternMatchFail (untangle s "Non-exhaustive guards in"))
563 irrefutPatError s = throw (PatternMatchFail (untangle s "Irrefutable pattern failed for pattern"))
564 recConError s = throw (RecConError (untangle s "Missing field in record construction"))
565 noMethodBindingError s = throw (NoMethodError (untangle s "No instance nor default method for class operation"))
566 patError s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))
570 data PatternMatchFail = PatternMatchFail String
571 INSTANCE_TYPEABLE0(PatternMatchFail,patternMatchFailTc,"PatternMatchFail")
573 instance Exception PatternMatchFail
575 instance Show PatternMatchFail where
576 showsPrec _ (PatternMatchFail err) = showString err
580 data RecSelError = RecSelError String
581 INSTANCE_TYPEABLE0(RecSelError,recSelErrorTc,"RecSelError")
583 instance Exception RecSelError
585 instance Show RecSelError where
586 showsPrec _ (RecSelError err) = showString err
590 data RecConError = RecConError String
591 INSTANCE_TYPEABLE0(RecConError,recConErrorTc,"RecConError")
593 instance Exception RecConError
595 instance Show RecConError where
596 showsPrec _ (RecConError err) = showString err
600 data RecUpdError = RecUpdError String
601 INSTANCE_TYPEABLE0(RecUpdError,recUpdErrorTc,"RecUpdError")
603 instance Exception RecUpdError
605 instance Show RecUpdError where
606 showsPrec _ (RecUpdError err) = showString err
610 data NoMethodError = NoMethodError String
611 INSTANCE_TYPEABLE0(NoMethodError,noMethodErrorTc,"NoMethodError")
613 instance Exception NoMethodError
615 instance Show NoMethodError where
616 showsPrec _ (NoMethodError err) = showString err
620 data NonTermination = NonTermination
621 INSTANCE_TYPEABLE0(NonTermination,nonTerminationTc,"NonTermination")
623 instance Exception NonTermination
625 instance Show NonTermination where
626 showsPrec _ NonTermination = showString "<<loop>>"
628 -- GHC's RTS calls this
629 nonTermination :: SomeException
630 nonTermination = toException NonTermination
634 data NestedAtomically = NestedAtomically
635 INSTANCE_TYPEABLE0(NestedAtomically,nestedAtomicallyTc,"NestedAtomically")
637 instance Exception NestedAtomically
639 instance Show NestedAtomically where
640 showsPrec _ NestedAtomically = showString "Control.Concurrent.STM.atomically was nested"
642 -- GHC's RTS calls this
643 nestedAtomically :: SomeException
644 nestedAtomically = toException NestedAtomically
648 instance Exception Dynamic