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,
133 #ifdef __GLASGOW_HASKELL__
138 import GHC.IOBase as ExceptionBase
139 import GHC.Exception hiding ( Exception )
144 import Hugs.Exception as ExceptionBase
152 import qualified System.IO.Error as H'98 (catch)
153 import System.IO.Error (ioError)
155 import DIOError -- defn of IOError type
156 import System (ExitCode())
157 import System.IO.Unsafe (unsafePerformIO)
158 import Unsafe.Coerce (unsafeCoerce)
160 -- minimum needed for nhc98 to pretend it has Exceptions
163 data Exception = IOException IOException
164 | ArithException ArithException
165 | ArrayException ArrayException
166 | AsyncException AsyncException
167 | ExitException ExitCode
170 class ({-Typeable e,-} Show e) => Exception e where
171 toException :: e -> SomeException
172 fromException :: SomeException -> Maybe e
174 data SomeException = forall e . Exception e => SomeException e
176 INSTANCE_TYPEABLE0(SomeException,someExceptionTc,"SomeException")
178 instance Show SomeException where
179 showsPrec p (SomeException e) = showsPrec p e
180 instance Exception SomeException where
184 type IOException = IOError
185 instance Exception IOError where
186 toException = SomeException
187 fromException (SomeException e) = Just (unsafeCoerce e)
189 instance Exception ExitCode where
190 toException = SomeException
191 fromException (SomeException e) = Just (unsafeCoerce e)
197 data PatternMatchFail
200 data BlockedOnDeadMVar
201 data BlockedIndefinitely
206 instance Show ArithException
207 instance Show ArrayException
208 instance Show AsyncException
209 instance Show AssertionFailed
210 instance Show PatternMatchFail
211 instance Show NoMethodError
212 instance Show Deadlock
213 instance Show BlockedOnDeadMVar
214 instance Show BlockedIndefinitely
215 instance Show ErrorCall
216 instance Show RecConError
217 instance Show RecSelError
218 instance Show RecUpdError
221 => IO a -- ^ The computation to run
222 -> (e -> IO a) -- ^ Handler to invoke if an exception is raised
224 catch io h = H'98.catch io (h . fromJust . fromException . toException)
226 throwIO :: Exception e => e -> IO a
227 throwIO = ioError . fromJust . fromException . toException
229 throw :: Exception e => e -> a
230 throw = unsafePerformIO . throwIO
232 evaluate :: a -> IO a
233 evaluate x = x `seq` return x
235 assert :: Bool -> a -> a
237 assert False _ = throw (toException (UserError "" "Assertion failed"))
241 #ifndef __GLASGOW_HASKELL__
242 -- Dummy definitions for implementations lacking asynchonous exceptions
244 block :: IO a -> IO a
246 unblock :: IO a -> IO a
249 blocked = return False
252 -----------------------------------------------------------------------------
253 -- Catching exceptions
255 -- |This is the simplest of the exception-catching functions. It
256 -- takes a single argument, runs it, and if an exception is raised
257 -- the \"handler\" is executed, with the value of the exception passed as an
258 -- argument. Otherwise, the result is returned as normal. For example:
260 -- > catch (openFile f ReadMode)
261 -- > (\e -> hPutStr stderr ("Couldn't open "++f++": " ++ show e))
263 -- For catching exceptions in pure (non-'IO') expressions, see the
264 -- function 'evaluate'.
266 -- Note that due to Haskell\'s unspecified evaluation order, an
267 -- expression may return one of several possible exceptions: consider
268 -- the expression @error \"urk\" + 1 \`div\` 0@. Does
269 -- 'catch' execute the handler passing
270 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
272 -- The answer is \"either\": 'catch' makes a
273 -- non-deterministic choice about which exception to catch. If you
274 -- call it again, you might get a different exception back. This is
275 -- ok, because 'catch' is an 'IO' computation.
277 -- Note that 'catch' catches all types of exceptions, and is generally
278 -- used for \"cleaning up\" before passing on the exception using
279 -- 'throwIO'. It is not good practice to discard the exception and
280 -- continue, without first checking the type of the exception (it
281 -- might be a 'ThreadKilled', for example). In this case it is usually better
282 -- to use 'catchJust' and select the kinds of exceptions to catch.
284 -- Also note that the "Prelude" also exports a function called
285 -- 'Prelude.catch' with a similar type to 'Control.Exception.catch',
286 -- except that the "Prelude" version only catches the IO and user
287 -- families of exceptions (as required by Haskell 98).
289 -- We recommend either hiding the "Prelude" version of 'Prelude.catch'
290 -- when importing "Control.Exception":
292 -- > import Prelude hiding (catch)
294 -- or importing "Control.Exception" qualified, to avoid name-clashes:
296 -- > import qualified Control.Exception as C
298 -- and then using @C.catch@
302 => IO a -- ^ The computation to run
303 -> (e -> IO a) -- ^ Handler to invoke if an exception is raised
305 catch = ExceptionBase.catchException
308 catches :: IO a -> [Handler a] -> IO a
309 catches io handlers = io `catch` catchesHandler handlers
311 catchesHandler :: [Handler a] -> SomeException -> IO a
312 catchesHandler handlers e = foldr tryHandler (throw e) handlers
313 where tryHandler (Handler handler) res
314 = case fromException e of
315 Just e' -> handler e'
318 data Handler a = forall e . Exception e => Handler (e -> IO a)
319 -- | The function 'catchJust' is like 'catch', but it takes an extra
320 -- argument which is an /exception predicate/, a function which
321 -- selects which type of exceptions we\'re interested in.
323 -- > result <- catchJust errorCalls thing_to_try handler
325 -- Any other exceptions which are not matched by the predicate
326 -- are re-raised, and may be caught by an enclosing
327 -- 'catch' or 'catchJust'.
330 => (e -> Maybe b) -- ^ Predicate to select exceptions
331 -> IO a -- ^ Computation to run
332 -> (b -> IO a) -- ^ Handler
334 catchJust p a handler = catch a handler'
335 where handler' e = case p e of
339 -- | A version of 'catch' with the arguments swapped around; useful in
340 -- situations where the code for the handler is shorter. For example:
342 -- > do handle (\e -> exitWith (ExitFailure 1)) $
344 handle :: Exception e => (e -> IO a) -> IO a -> IO a
347 -- | A version of 'catchJust' with the arguments swapped around (see
349 handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a
350 handleJust p = flip (catchJust p)
352 -----------------------------------------------------------------------------
355 -- | This function maps one exception into another as proposed in the
356 -- paper \"A semantics for imprecise exceptions\".
358 -- Notice that the usage of 'unsafePerformIO' is safe here.
360 mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a
361 mapException f v = unsafePerformIO (catch (evaluate v)
364 -----------------------------------------------------------------------------
365 -- 'try' and variations.
367 -- | Similar to 'catch', but returns an 'Either' result which is
368 -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an
369 -- exception was raised and its value is @e@.
371 -- > try a = catch (Right `liftM` a) (return . Left)
373 -- Note: as with 'catch', it is only polite to use this variant if you intend
374 -- to re-throw the exception after performing whatever cleanup is needed.
375 -- Otherwise, 'tryJust' is generally considered to be better.
377 -- Also note that "System.IO.Error" also exports a function called
378 -- 'System.IO.Error.try' with a similar type to 'Control.Exception.try',
379 -- except that it catches only the IO and user families of exceptions
380 -- (as required by the Haskell 98 @IO@ module).
382 try :: Exception e => IO a -> IO (Either e a)
383 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
385 -- | A variant of 'try' that takes an exception predicate to select
386 -- which exceptions are caught (c.f. 'catchJust'). If the exception
387 -- does not match the predicate, it is re-thrown.
388 tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)
392 Right v -> return (Right v)
393 Left e -> case p e of
395 Just b -> return (Left b)
397 onException :: IO a -> IO b -> IO a
398 onException io what = io `catch` \e -> do what
399 throw (e :: SomeException)
401 -----------------------------------------------------------------------------
402 -- Some Useful Functions
404 -- | When you want to acquire a resource, do some work with it, and
405 -- then release the resource, it is a good idea to use 'bracket',
406 -- because 'bracket' will install the necessary exception handler to
407 -- release the resource in the event that an exception is raised
408 -- during the computation. If an exception is raised, then 'bracket' will
409 -- re-raise the exception (after performing the release).
411 -- A common example is opening a file:
414 -- > (openFile "filename" ReadMode)
416 -- > (\handle -> do { ... })
418 -- The arguments to 'bracket' are in this order so that we can partially apply
421 -- > withFile name mode = bracket (openFile name mode) hClose
425 :: IO a -- ^ computation to run first (\"acquire resource\")
426 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
427 -> (a -> IO c) -- ^ computation to run in-between
428 -> IO c -- returns the value from the in-between computation
429 bracket before after thing =
432 r <- unblock (thing a) `onException` after a
438 -- | A specialised variant of 'bracket' with just a computation to run
441 finally :: IO a -- ^ computation to run first
442 -> IO b -- ^ computation to run afterward (even if an exception
444 -> IO a -- returns the value from the first computation
447 r <- unblock a `onException` sequel
452 -- | A variant of 'bracket' where the return value from the first computation
454 bracket_ :: IO a -> IO b -> IO c -> IO c
455 bracket_ before after thing = bracket before (const after) (const thing)
457 -- | Like bracket, but only performs the final action if there was an
458 -- exception raised by the in-between computation.
460 :: IO a -- ^ computation to run first (\"acquire resource\")
461 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
462 -> (a -> IO c) -- ^ computation to run in-between
463 -> IO c -- returns the value from the in-between computation
464 bracketOnError before after thing =
467 unblock (thing a) `onException` after a
470 -- -----------------------------------------------------------------------------
471 -- Asynchronous exceptions
475 #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
476 external influences, and can be raised at any point during execution.
477 'StackOverflow' and 'HeapOverflow' are two examples of
478 system-generated asynchronous exceptions.
480 The primary source of asynchronous exceptions, however, is
483 > throwTo :: ThreadId -> Exception -> IO ()
485 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
486 running thread to raise an arbitrary exception in another thread. The
487 exception is therefore asynchronous with respect to the target thread,
488 which could be doing anything at the time it receives the exception.
489 Great care should be taken with asynchronous exceptions; it is all too
490 easy to introduce race conditions by the over zealous use of
495 There\'s an implied 'block' around every exception handler in a call
496 to one of the 'catch' family of functions. This is because that is
497 what you want most of the time - it eliminates a common race condition
498 in starting an exception handler, because there may be no exception
499 handler on the stack to handle another exception if one arrives
500 immediately. If asynchronous exceptions are blocked on entering the
501 handler, though, we have time to install a new exception handler
502 before being interrupted. If this weren\'t the default, one would have
503 to write something like
506 > catch (unblock (...))
510 If you need to unblock asynchronous exceptions again in the exception
511 handler, just use 'unblock' as normal.
513 Note that 'try' and friends /do not/ have a similar default, because
514 there is no exception handler in this case. If you want to use 'try'
515 in an asynchronous-exception-safe way, you will need to use
521 Some operations are /interruptible/, which means that they can receive
522 asynchronous exceptions even in the scope of a 'block'. Any function
523 which may itself block is defined as interruptible; this includes
524 'Control.Concurrent.MVar.takeMVar'
525 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
526 and most operations which perform
527 some I\/O with the outside world. The reason for having
528 interruptible operations is so that we can write things like
532 > catch (unblock (...))
536 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
538 combination could lead to deadlock, because the thread itself would be
539 blocked in a state where it can\'t receive any asynchronous exceptions.
540 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
541 safe in the knowledge that the thread can receive exceptions right up
542 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
543 Similar arguments apply for other interruptible operations like
544 'System.IO.openFile'.
547 #if !(__GLASGOW_HASKELL__ || __NHC__)
548 assert :: Bool -> a -> a
550 assert False _ = throw (AssertionFailed "")
554 recSelError, recConError, irrefutPatError, runtimeError,
555 nonExhaustiveGuardsError, patError, noMethodBindingError
556 :: Addr# -> a -- All take a UTF8-encoded C string
558 recSelError s = throw (RecSelError (unpackCStringUtf8# s)) -- No location info unfortunately
559 runtimeError s = error (unpackCStringUtf8# s) -- No location info unfortunately
561 nonExhaustiveGuardsError s = throw (PatternMatchFail (untangle s "Non-exhaustive guards in"))
562 irrefutPatError s = throw (PatternMatchFail (untangle s "Irrefutable pattern failed for pattern"))
563 recConError s = throw (RecConError (untangle s "Missing field in record construction"))
564 noMethodBindingError s = throw (NoMethodError (untangle s "No instance nor default method for class operation"))
565 patError s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))
569 data PatternMatchFail = PatternMatchFail String
570 INSTANCE_TYPEABLE0(PatternMatchFail,patternMatchFailTc,"PatternMatchFail")
572 instance Exception PatternMatchFail
574 instance Show PatternMatchFail where
575 showsPrec _ (PatternMatchFail err) = showString err
579 data RecSelError = RecSelError String
580 INSTANCE_TYPEABLE0(RecSelError,recSelErrorTc,"RecSelError")
582 instance Exception RecSelError
584 instance Show RecSelError where
585 showsPrec _ (RecSelError err) = showString err
589 data RecConError = RecConError String
590 INSTANCE_TYPEABLE0(RecConError,recConErrorTc,"RecConError")
592 instance Exception RecConError
594 instance Show RecConError where
595 showsPrec _ (RecConError err) = showString err
599 data RecUpdError = RecUpdError String
600 INSTANCE_TYPEABLE0(RecUpdError,recUpdErrorTc,"RecUpdError")
602 instance Exception RecUpdError
604 instance Show RecUpdError where
605 showsPrec _ (RecUpdError err) = showString err
609 data NoMethodError = NoMethodError String
610 INSTANCE_TYPEABLE0(NoMethodError,noMethodErrorTc,"NoMethodError")
612 instance Exception NoMethodError
614 instance Show NoMethodError where
615 showsPrec _ (NoMethodError err) = showString err
619 data NonTermination = NonTermination
620 INSTANCE_TYPEABLE0(NonTermination,nonTerminationTc,"NonTermination")
622 instance Exception NonTermination
624 instance Show NonTermination where
625 showsPrec _ NonTermination = showString "<<loop>>"
627 -- GHC's RTS calls this
628 nonTermination :: SomeException
629 nonTermination = toException NonTermination
633 data NestedAtomically = NestedAtomically
634 INSTANCE_TYPEABLE0(NestedAtomically,nestedAtomicallyTc,"NestedAtomically")
636 instance Exception NestedAtomically
638 instance Show NestedAtomically where
639 showsPrec _ NestedAtomically = showString "Control.Concurrent.STM.atomically was nested"
641 -- GHC's RTS calls this
642 nestedAtomically :: SomeException
643 nestedAtomically = toException NestedAtomically
647 instance Exception Dynamic