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)
194 data PatternMatchFail
197 data BlockedOnDeadMVar
198 data BlockedIndefinitely
203 instance Show ArithException
204 instance Show ArrayException
205 instance Show AsyncException
206 instance Show AssertionFailed
207 instance Show PatternMatchFail
208 instance Show NoMethodError
209 instance Show Deadlock
210 instance Show BlockedOnDeadMVar
211 instance Show BlockedIndefinitely
212 instance Show ErrorCall
213 instance Show RecConError
214 instance Show RecSelError
215 instance Show RecUpdError
218 => IO a -- ^ The computation to run
219 -> (e -> IO a) -- ^ Handler to invoke if an exception is raised
221 catch io h = H'98.catch io (h . fromJust . fromException . toException)
223 throwIO :: Exception e => e -> IO a
224 throwIO = ioError . fromJust . fromException . toException
226 throw :: Exception e => e -> a
227 throw = unsafePerformIO . throwIO
229 evaluate :: a -> IO a
230 evaluate x = x `seq` return x
232 assert :: Bool -> a -> a
234 assert False _ = throw (toException (UserError "" "Assertion failed"))
238 #ifndef __GLASGOW_HASKELL__
239 -- Dummy definitions for implementations lacking asynchonous exceptions
241 block :: IO a -> IO a
243 unblock :: IO a -> IO a
246 blocked = return False
249 -----------------------------------------------------------------------------
250 -- Catching exceptions
252 -- |This is the simplest of the exception-catching functions. It
253 -- takes a single argument, runs it, and if an exception is raised
254 -- the \"handler\" is executed, with the value of the exception passed as an
255 -- argument. Otherwise, the result is returned as normal. For example:
257 -- > catch (openFile f ReadMode)
258 -- > (\e -> hPutStr stderr ("Couldn't open "++f++": " ++ show e))
260 -- For catching exceptions in pure (non-'IO') expressions, see the
261 -- function 'evaluate'.
263 -- Note that due to Haskell\'s unspecified evaluation order, an
264 -- expression may return one of several possible exceptions: consider
265 -- the expression @error \"urk\" + 1 \`div\` 0@. Does
266 -- 'catch' execute the handler passing
267 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
269 -- The answer is \"either\": 'catch' makes a
270 -- non-deterministic choice about which exception to catch. If you
271 -- call it again, you might get a different exception back. This is
272 -- ok, because 'catch' is an 'IO' computation.
274 -- Note that 'catch' catches all types of exceptions, and is generally
275 -- used for \"cleaning up\" before passing on the exception using
276 -- 'throwIO'. It is not good practice to discard the exception and
277 -- continue, without first checking the type of the exception (it
278 -- might be a 'ThreadKilled', for example). In this case it is usually better
279 -- to use 'catchJust' and select the kinds of exceptions to catch.
281 -- Also note that the "Prelude" also exports a function called
282 -- 'Prelude.catch' with a similar type to 'Control.Exception.catch',
283 -- except that the "Prelude" version only catches the IO and user
284 -- families of exceptions (as required by Haskell 98).
286 -- We recommend either hiding the "Prelude" version of 'Prelude.catch'
287 -- when importing "Control.Exception":
289 -- > import Prelude hiding (catch)
291 -- or importing "Control.Exception" qualified, to avoid name-clashes:
293 -- > import qualified Control.Exception as C
295 -- and then using @C.catch@
299 => IO a -- ^ The computation to run
300 -> (e -> IO a) -- ^ Handler to invoke if an exception is raised
302 catch = ExceptionBase.catchException
305 catches :: IO a -> [Handler a] -> IO a
306 catches io handlers = io `catch` catchesHandler handlers
308 catchesHandler :: [Handler a] -> SomeException -> IO a
309 catchesHandler handlers e = foldr tryHandler (throw e) handlers
310 where tryHandler (Handler handler) res
311 = case fromException e of
312 Just e' -> handler e'
315 data Handler a = forall e . Exception e => Handler (e -> IO a)
316 -- | The function 'catchJust' is like 'catch', but it takes an extra
317 -- argument which is an /exception predicate/, a function which
318 -- selects which type of exceptions we\'re interested in.
320 -- > result <- catchJust errorCalls thing_to_try handler
322 -- Any other exceptions which are not matched by the predicate
323 -- are re-raised, and may be caught by an enclosing
324 -- 'catch' or 'catchJust'.
327 => (e -> Maybe b) -- ^ Predicate to select exceptions
328 -> IO a -- ^ Computation to run
329 -> (b -> IO a) -- ^ Handler
331 catchJust p a handler = catch a handler'
332 where handler' e = case p e of
336 -- | A version of 'catch' with the arguments swapped around; useful in
337 -- situations where the code for the handler is shorter. For example:
339 -- > do handle (\e -> exitWith (ExitFailure 1)) $
341 handle :: Exception e => (e -> IO a) -> IO a -> IO a
344 -- | A version of 'catchJust' with the arguments swapped around (see
346 handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a
347 handleJust p = flip (catchJust p)
349 -----------------------------------------------------------------------------
352 -- | This function maps one exception into another as proposed in the
353 -- paper \"A semantics for imprecise exceptions\".
355 -- Notice that the usage of 'unsafePerformIO' is safe here.
357 mapException :: Exception e => (e -> e) -> a -> a
358 mapException f v = unsafePerformIO (catch (evaluate v)
361 -----------------------------------------------------------------------------
362 -- 'try' and variations.
364 -- | Similar to 'catch', but returns an 'Either' result which is
365 -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an
366 -- exception was raised and its value is @e@.
368 -- > try a = catch (Right `liftM` a) (return . Left)
370 -- Note: as with 'catch', it is only polite to use this variant if you intend
371 -- to re-throw the exception after performing whatever cleanup is needed.
372 -- Otherwise, 'tryJust' is generally considered to be better.
374 -- Also note that "System.IO.Error" also exports a function called
375 -- 'System.IO.Error.try' with a similar type to 'Control.Exception.try',
376 -- except that it catches only the IO and user families of exceptions
377 -- (as required by the Haskell 98 @IO@ module).
379 try :: Exception e => IO a -> IO (Either e a)
380 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
382 -- | A variant of 'try' that takes an exception predicate to select
383 -- which exceptions are caught (c.f. 'catchJust'). If the exception
384 -- does not match the predicate, it is re-thrown.
385 tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)
389 Right v -> return (Right v)
390 Left e -> case p e of
392 Just b -> return (Left b)
394 onException :: IO a -> IO b -> IO a
395 onException io what = io `catch` \e -> do what
396 throw (e :: SomeException)
398 -----------------------------------------------------------------------------
399 -- Some Useful Functions
401 -- | When you want to acquire a resource, do some work with it, and
402 -- then release the resource, it is a good idea to use 'bracket',
403 -- because 'bracket' will install the necessary exception handler to
404 -- release the resource in the event that an exception is raised
405 -- during the computation. If an exception is raised, then 'bracket' will
406 -- re-raise the exception (after performing the release).
408 -- A common example is opening a file:
411 -- > (openFile "filename" ReadMode)
413 -- > (\handle -> do { ... })
415 -- The arguments to 'bracket' are in this order so that we can partially apply
418 -- > withFile name mode = bracket (openFile name mode) hClose
422 :: IO a -- ^ computation to run first (\"acquire resource\")
423 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
424 -> (a -> IO c) -- ^ computation to run in-between
425 -> IO c -- returns the value from the in-between computation
426 bracket before after thing =
429 r <- unblock (thing a) `onException` after a
435 -- | A specialised variant of 'bracket' with just a computation to run
438 finally :: IO a -- ^ computation to run first
439 -> IO b -- ^ computation to run afterward (even if an exception
441 -> IO a -- returns the value from the first computation
444 r <- unblock a `onException` sequel
449 -- | A variant of 'bracket' where the return value from the first computation
451 bracket_ :: IO a -> IO b -> IO c -> IO c
452 bracket_ before after thing = bracket before (const after) (const thing)
454 -- | Like bracket, but only performs the final action if there was an
455 -- exception raised by the in-between computation.
457 :: IO a -- ^ computation to run first (\"acquire resource\")
458 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
459 -> (a -> IO c) -- ^ computation to run in-between
460 -> IO c -- returns the value from the in-between computation
461 bracketOnError before after thing =
464 unblock (thing a) `onException` after a
467 -- -----------------------------------------------------------------------------
468 -- Asynchronous exceptions
472 #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
473 external influences, and can be raised at any point during execution.
474 'StackOverflow' and 'HeapOverflow' are two examples of
475 system-generated asynchronous exceptions.
477 The primary source of asynchronous exceptions, however, is
480 > throwTo :: ThreadId -> Exception -> IO ()
482 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
483 running thread to raise an arbitrary exception in another thread. The
484 exception is therefore asynchronous with respect to the target thread,
485 which could be doing anything at the time it receives the exception.
486 Great care should be taken with asynchronous exceptions; it is all too
487 easy to introduce race conditions by the over zealous use of
492 There\'s an implied 'block' around every exception handler in a call
493 to one of the 'catch' family of functions. This is because that is
494 what you want most of the time - it eliminates a common race condition
495 in starting an exception handler, because there may be no exception
496 handler on the stack to handle another exception if one arrives
497 immediately. If asynchronous exceptions are blocked on entering the
498 handler, though, we have time to install a new exception handler
499 before being interrupted. If this weren\'t the default, one would have
500 to write something like
503 > catch (unblock (...))
507 If you need to unblock asynchronous exceptions again in the exception
508 handler, just use 'unblock' as normal.
510 Note that 'try' and friends /do not/ have a similar default, because
511 there is no exception handler in this case. If you want to use 'try'
512 in an asynchronous-exception-safe way, you will need to use
518 Some operations are /interruptible/, which means that they can receive
519 asynchronous exceptions even in the scope of a 'block'. Any function
520 which may itself block is defined as interruptible; this includes
521 'Control.Concurrent.MVar.takeMVar'
522 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
523 and most operations which perform
524 some I\/O with the outside world. The reason for having
525 interruptible operations is so that we can write things like
529 > catch (unblock (...))
533 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
535 combination could lead to deadlock, because the thread itself would be
536 blocked in a state where it can\'t receive any asynchronous exceptions.
537 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
538 safe in the knowledge that the thread can receive exceptions right up
539 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
540 Similar arguments apply for other interruptible operations like
541 'System.IO.openFile'.
544 #if !(__GLASGOW_HASKELL__ || __NHC__)
545 assert :: Bool -> a -> a
547 assert False _ = throw (AssertionFailed "")
551 recSelError, recConError, irrefutPatError, runtimeError,
552 nonExhaustiveGuardsError, patError, noMethodBindingError
553 :: Addr# -> a -- All take a UTF8-encoded C string
555 recSelError s = throw (RecSelError (unpackCStringUtf8# s)) -- No location info unfortunately
556 runtimeError s = error (unpackCStringUtf8# s) -- No location info unfortunately
558 nonExhaustiveGuardsError s = throw (PatternMatchFail (untangle s "Non-exhaustive guards in"))
559 irrefutPatError s = throw (PatternMatchFail (untangle s "Irrefutable pattern failed for pattern"))
560 recConError s = throw (RecConError (untangle s "Missing field in record construction"))
561 noMethodBindingError s = throw (NoMethodError (untangle s "No instance nor default method for class operation"))
562 patError s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))
566 data PatternMatchFail = PatternMatchFail String
567 INSTANCE_TYPEABLE0(PatternMatchFail,patternMatchFailTc,"PatternMatchFail")
569 instance Exception PatternMatchFail
571 instance Show PatternMatchFail where
572 showsPrec _ (PatternMatchFail err) = showString err
576 data RecSelError = RecSelError String
577 INSTANCE_TYPEABLE0(RecSelError,recSelErrorTc,"RecSelError")
579 instance Exception RecSelError
581 instance Show RecSelError where
582 showsPrec _ (RecSelError err) = showString err
586 data RecConError = RecConError String
587 INSTANCE_TYPEABLE0(RecConError,recConErrorTc,"RecConError")
589 instance Exception RecConError
591 instance Show RecConError where
592 showsPrec _ (RecConError err) = showString err
596 data RecUpdError = RecUpdError String
597 INSTANCE_TYPEABLE0(RecUpdError,recUpdErrorTc,"RecUpdError")
599 instance Exception RecUpdError
601 instance Show RecUpdError where
602 showsPrec _ (RecUpdError err) = showString err
606 data NoMethodError = NoMethodError String
607 INSTANCE_TYPEABLE0(NoMethodError,noMethodErrorTc,"NoMethodError")
609 instance Exception NoMethodError
611 instance Show NoMethodError where
612 showsPrec _ (NoMethodError err) = showString err
616 data NonTermination = NonTermination
617 INSTANCE_TYPEABLE0(NonTermination,nonTerminationTc,"NonTermination")
619 instance Exception NonTermination
621 instance Show NonTermination where
622 showsPrec _ NonTermination = showString "<<loop>>"
624 -- GHC's RTS calls this
625 nonTermination :: SomeException
626 nonTermination = toException NonTermination
630 data NestedAtomically = NestedAtomically
631 INSTANCE_TYPEABLE0(NestedAtomically,nestedAtomicallyTc,"NestedAtomically")
633 instance Exception NestedAtomically
635 instance Show NestedAtomically where
636 showsPrec _ NestedAtomically = showString "Control.Concurrent.STM.atomically was nested"
638 -- GHC's RTS calls this
639 nestedAtomically :: SomeException
640 nestedAtomically = toException NestedAtomically
644 instance Exception Dynamic