1 -----------------------------------------------------------------------------
3 -- Module : Control.Exception
4 -- Copyright : (c) The University of Glasgow 2001
5 -- License : BSD-style (see the file libraries/base/LICENSE)
7 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : non-portable (extended exceptions)
11 -- This module provides support for raising and catching both built-in
12 -- and user-defined exceptions.
14 -- In addition to exceptions thrown by 'IO' operations, exceptions may
15 -- be thrown by pure code (imprecise exceptions) or by external events
16 -- (asynchronous exceptions), but may only be caught in the 'IO' monad.
17 -- For more details, see:
19 -- * /A semantics for imprecise exceptions/, by Simon Peyton Jones,
20 -- Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson,
23 -- * /Asynchronous exceptions in Haskell/, by Simon Marlow, Simon Peyton
24 -- Jones, Andy Moran and John Reppy, in /PLDI'01/.
26 -----------------------------------------------------------------------------
28 module Control.Exception (
30 -- * The Exception type
31 Exception(..), -- instance Eq, Ord, Show, Typeable
32 IOException, -- instance Eq, Ord, Show, Typeable
33 ArithException(..), -- instance Eq, Ord, Show, Typeable
34 ArrayException(..), -- instance Eq, Ord, Show, Typeable
35 AsyncException(..), -- instance Eq, Ord, Show, Typeable
37 -- * Throwing exceptions
38 throwIO, -- :: Exception -> IO a
39 throw, -- :: Exception -> a
40 ioError, -- :: IOError -> IO a
41 #ifdef __GLASGOW_HASKELL__
42 throwTo, -- :: ThreadId -> Exception -> a
45 -- * Catching Exceptions
47 -- |There are several functions for catching and examining
48 -- exceptions; all of them may only be used from within the
51 -- ** The @catch@ functions
52 catch, -- :: IO a -> (Exception -> IO a) -> IO a
54 catchJust, -- :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a
56 -- ** The @handle@ functions
57 handle, -- :: (Exception -> IO a) -> IO a -> IO a
58 handleJust,-- :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
60 -- ** The @try@ functions
61 try, -- :: IO a -> IO (Either Exception a)
62 tryJust, -- :: (Exception -> Maybe b) -> a -> IO (Either b a)
64 -- ** The @evaluate@ function
65 evaluate, -- :: a -> IO a
67 -- ** The @mapException@ function
68 mapException, -- :: (Exception -> Exception) -> a -> a
70 -- ** Exception predicates
74 ioErrors, -- :: Exception -> Maybe IOError
75 arithExceptions, -- :: Exception -> Maybe ArithException
76 errorCalls, -- :: Exception -> Maybe String
77 dynExceptions, -- :: Exception -> Maybe Dynamic
78 assertions, -- :: Exception -> Maybe String
79 asyncExceptions, -- :: Exception -> Maybe AsyncException
80 userErrors, -- :: Exception -> Maybe String
82 -- * Dynamic exceptions
85 throwDyn, -- :: Typeable ex => ex -> b
86 #ifdef __GLASGOW_HASKELL__
87 throwDynTo, -- :: Typeable ex => ThreadId -> ex -> b
89 catchDyn, -- :: Typeable ex => IO a -> (ex -> IO a) -> IO a
91 -- * Asynchronous Exceptions
95 -- ** Asynchronous exception control
97 -- |The following two functions allow a thread to control delivery of
98 -- asynchronous exceptions during a critical region.
100 block, -- :: IO a -> IO a
101 unblock, -- :: IO a -> IO a
102 blocked, -- :: IO Bool
104 -- *** Applying @block@ to an exception handler
108 -- *** Interruptible operations
114 assert, -- :: Bool -> a -> a
118 bracket, -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO ()
119 bracket_, -- :: IO a -> IO b -> IO c -> IO ()
122 finally, -- :: IO a -> IO b -> IO a
124 #ifdef __GLASGOW_HASKELL__
125 setUncaughtExceptionHandler, -- :: (Exception -> IO ()) -> IO ()
126 getUncaughtExceptionHandler -- :: IO (Exception -> IO ())
130 #ifdef __GLASGOW_HASKELL__
131 import GHC.IOBase as ExceptionBase hiding ( catch )
132 import GHC.Exception hiding ( Exception )
133 import GHC.Conc ( throwTo, ThreadId )
134 import Data.IORef ( IORef, newIORef, readIORef, writeIORef )
135 import Foreign.C.String ( CString, withCString )
136 import System.IO ( stdout, hFlush )
140 import Hugs.Exception as ExceptionBase
143 import Prelude hiding ( catch )
144 import System.IO.Error hiding ( catch, try )
145 import System.IO.Unsafe (unsafePerformIO)
149 import qualified System.IO.Error as H'98 (catch)
150 import System.IO.Error (ioError)
152 import DIOError -- defn of IOError type
153 import System (ExitCode())
155 -- minimum needed for nhc98 to pretend it has Exceptions
156 data Exception = IOException IOException
157 | ArithException ArithException
158 | ArrayException ArrayException
159 | AsyncException AsyncException
160 | ExitException ExitCode
162 type IOException = IOError
166 instance Show ArithException
167 instance Show ArrayException
168 instance Show AsyncException
170 catch :: IO a -> (Exception -> IO a) -> IO a
171 a `catch` b = a `H'98.catch` (b . IOException)
173 throwIO :: Exception -> IO a
174 throwIO (IOException e) = ioError e
175 throwIO _ = ioError (UserError "Control.Exception.throwIO"
177 throw :: Exception -> a
178 throw = unsafePerformIO . throwIO
180 evaluate :: a -> IO a
181 evaluate x = x `seq` return x
183 ioErrors :: Exception -> Maybe IOError
184 ioErrors (IOException e) = Just e
186 arithExceptions :: Exception -> Maybe ArithException
187 arithExceptions (ArithException e) = Just e
188 arithExceptions _ = Nothing
189 errorCalls :: Exception -> Maybe String
190 errorCalls = const Nothing
191 dynExceptions :: Exception -> Maybe Dynamic
192 dynExceptions = const Nothing
193 assertions :: Exception -> Maybe String
194 assertions = const Nothing
195 asyncExceptions :: Exception -> Maybe AsyncException
196 asyncExceptions = const Nothing
197 userErrors :: Exception -> Maybe String
198 userErrors (IOException (UserError _ s)) = Just s
199 userErrors _ = Nothing
201 assert :: Bool -> a -> a
203 assert False _ = throw (IOException (UserError "" "Assertion failed"))
206 #ifndef __GLASGOW_HASKELL__
207 -- Dummy definitions for implementations lacking asynchonous exceptions
209 block :: IO a -> IO a
211 unblock :: IO a -> IO a
214 blocked = return False
217 -----------------------------------------------------------------------------
218 -- Catching exceptions
220 -- |This is the simplest of the exception-catching functions. It
221 -- takes a single argument, runs it, and if an exception is raised
222 -- the \"handler\" is executed, with the value of the exception passed as an
223 -- argument. Otherwise, the result is returned as normal. For example:
225 -- > catch (openFile f ReadMode)
226 -- > (\e -> hPutStr stderr ("Couldn't open "++f++": " ++ show e))
228 -- For catching exceptions in pure (non-'IO') expressions, see the
229 -- function 'evaluate'.
231 -- Note that due to Haskell\'s unspecified evaluation order, an
232 -- expression may return one of several possible exceptions: consider
233 -- the expression @error \"urk\" + 1 \`div\` 0@. Does
234 -- 'catch' execute the handler passing
235 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
237 -- The answer is \"either\": 'catch' makes a
238 -- non-deterministic choice about which exception to catch. If you
239 -- call it again, you might get a different exception back. This is
240 -- ok, because 'catch' is an 'IO' computation.
242 -- Note that 'catch' catches all types of exceptions, and is generally
243 -- used for \"cleaning up\" before passing on the exception using
244 -- 'throwIO'. It is not good practice to discard the exception and
245 -- continue, without first checking the type of the exception (it
246 -- might be a 'ThreadKilled', for example). In this case it is usually better
247 -- to use 'catchJust' and select the kinds of exceptions to catch.
249 -- Also note that the "Prelude" also exports a function called
250 -- 'Prelude.catch' with a similar type to 'Control.Exception.catch',
251 -- except that the "Prelude" version only catches the IO and user
252 -- families of exceptions (as required by Haskell 98).
254 -- We recommend either hiding the "Prelude" version of 'Prelude.catch'
255 -- when importing "Control.Exception":
257 -- > import Prelude hiding (catch)
259 -- or importing "Control.Exception" qualified, to avoid name-clashes:
261 -- > import qualified Control.Exception as C
263 -- and then using @C.catch@
266 catch :: IO a -- ^ The computation to run
267 -> (Exception -> IO a) -- ^ Handler to invoke if an exception is raised
269 catch = ExceptionBase.catchException
271 -- | The function 'catchJust' is like 'catch', but it takes an extra
272 -- argument which is an /exception predicate/, a function which
273 -- selects which type of exceptions we\'re interested in. There are
274 -- some predefined exception predicates for useful subsets of
275 -- exceptions: 'ioErrors', 'arithExceptions', and so on. For example,
276 -- to catch just calls to the 'error' function, we could use
278 -- > result <- catchJust errorCalls thing_to_try handler
280 -- Any other exceptions which are not matched by the predicate
281 -- are re-raised, and may be caught by an enclosing
282 -- 'catch' or 'catchJust'.
284 :: (Exception -> Maybe b) -- ^ Predicate to select exceptions
285 -> IO a -- ^ Computation to run
286 -> (b -> IO a) -- ^ Handler
288 catchJust p a handler = catch a handler'
289 where handler' e = case p e of
293 -- | A version of 'catch' with the arguments swapped around; useful in
294 -- situations where the code for the handler is shorter. For example:
296 -- > do handle (\e -> exitWith (ExitFailure 1)) $
298 handle :: (Exception -> IO a) -> IO a -> IO a
301 -- | A version of 'catchJust' with the arguments swapped around (see
303 handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
304 handleJust p = flip (catchJust p)
306 -----------------------------------------------------------------------------
309 -- | This function maps one exception into another as proposed in the
310 -- paper \"A semantics for imprecise exceptions\".
312 -- Notice that the usage of 'unsafePerformIO' is safe here.
314 mapException :: (Exception -> Exception) -> a -> a
315 mapException f v = unsafePerformIO (catch (evaluate v)
318 -----------------------------------------------------------------------------
319 -- 'try' and variations.
321 -- | Similar to 'catch', but returns an 'Either' result which is
322 -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an
323 -- exception was raised and its value is @e@.
325 -- > try a = catch (Right `liftM` a) (return . Left)
327 -- Note: as with 'catch', it is only polite to use this variant if you intend
328 -- to re-throw the exception after performing whatever cleanup is needed.
329 -- Otherwise, 'tryJust' is generally considered to be better.
331 -- Also note that "System.IO.Error" also exports a function called
332 -- 'System.IO.Error.try' with a similar type to 'Control.Exception.try',
333 -- except that it catches only the IO and user families of exceptions
334 -- (as required by the Haskell 98 @IO@ module).
336 try :: IO a -> IO (Either Exception a)
337 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
339 -- | A variant of 'try' that takes an exception predicate to select
340 -- which exceptions are caught (c.f. 'catchJust'). If the exception
341 -- does not match the predicate, it is re-thrown.
342 tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a)
346 Right v -> return (Right v)
347 Left e -> case p e of
349 Just b -> return (Left b)
351 -----------------------------------------------------------------------------
352 -- Dynamic exceptions
355 -- #DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an
356 -- interface for throwing and catching exceptions of type 'Dynamic'
357 -- (see "Data.Dynamic") which allows exception values of any type in
358 -- the 'Typeable' class to be thrown and caught.
360 -- | Raise any value as an exception, provided it is in the
362 throwDyn :: Typeable exception => exception -> b
364 throwDyn exception = throw (IOException (UserError "" "dynamic exception"))
366 throwDyn exception = throw (DynException (toDyn exception))
369 #ifdef __GLASGOW_HASKELL__
370 -- | A variant of 'throwDyn' that throws the dynamic exception to an
371 -- arbitrary thread (GHC only: c.f. 'throwTo').
372 throwDynTo :: Typeable exception => ThreadId -> exception -> IO ()
373 throwDynTo t exception = throwTo t (DynException (toDyn exception))
374 #endif /* __GLASGOW_HASKELL__ */
376 -- | Catch dynamic exceptions of the required type. All other
377 -- exceptions are re-thrown, including dynamic exceptions of the wrong
380 -- When using dynamic exceptions it is advisable to define a new
381 -- datatype to use for your exception type, to avoid possible clashes
382 -- with dynamic exceptions used in other libraries.
384 catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a
386 catchDyn m k = m -- can't catch dyn exceptions in nhc98
388 catchDyn m k = catchException m handle
389 where handle ex = case ex of
390 (DynException dyn) ->
391 case fromDynamic dyn of
392 Just exception -> k exception
397 -----------------------------------------------------------------------------
398 -- Exception Predicates
401 -- These pre-defined predicates may be used as the first argument to
402 -- 'catchJust', 'tryJust', or 'handleJust' to select certain common
403 -- classes of exceptions.
405 ioErrors :: Exception -> Maybe IOError
406 arithExceptions :: Exception -> Maybe ArithException
407 errorCalls :: Exception -> Maybe String
408 assertions :: Exception -> Maybe String
409 dynExceptions :: Exception -> Maybe Dynamic
410 asyncExceptions :: Exception -> Maybe AsyncException
411 userErrors :: Exception -> Maybe String
413 ioErrors (IOException e) = Just e
416 arithExceptions (ArithException e) = Just e
417 arithExceptions _ = Nothing
419 errorCalls (ErrorCall e) = Just e
420 errorCalls _ = Nothing
422 assertions (AssertionFailed e) = Just e
423 assertions _ = Nothing
425 dynExceptions (DynException e) = Just e
426 dynExceptions _ = Nothing
428 asyncExceptions (AsyncException e) = Just e
429 asyncExceptions _ = Nothing
431 userErrors (IOException e) | isUserError e = Just (ioeGetErrorString e)
432 userErrors _ = Nothing
434 -----------------------------------------------------------------------------
435 -- Some Useful Functions
437 -- | When you want to acquire a resource, do some work with it, and
438 -- then release the resource, it is a good idea to use 'bracket',
439 -- because 'bracket' will install the necessary exception handler to
440 -- release the resource in the event that an exception is raised
441 -- during the computation. If an exception is raised, then 'bracket' will
442 -- re-raise the exception (after performing the release).
444 -- A common example is opening a file:
447 -- > (openFile "filename" ReadMode)
449 -- > (\handle -> do { ... })
451 -- The arguments to 'bracket' are in this order so that we can partially apply
454 -- > withFile name mode = bracket (openFile name mode) hClose
458 :: IO a -- ^ computation to run first (\"acquire resource\")
459 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
460 -> (a -> IO c) -- ^ computation to run in-between
461 -> IO c -- returns the value from the in-between computation
462 bracket before after thing =
467 (\e -> do { after a; throw e })
473 -- | A specialised variant of 'bracket' with just a computation to run
476 finally :: IO a -- ^ computation to run first
477 -> IO b -- ^ computation to run afterward (even if an exception
479 -> IO a -- returns the value from the first computation
484 (\e -> do { sequel; throw e })
489 -- | A variant of 'bracket' where the return value from the first computation
491 bracket_ :: IO a -> IO b -> IO c -> IO c
492 bracket_ before after thing = bracket before (const after) (const thing)
494 -- | Like bracket, but only performs the final action if there was an
495 -- exception raised by the in-between computation.
497 :: IO a -- ^ computation to run first (\"acquire resource\")
498 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
499 -> (a -> IO c) -- ^ computation to run in-between
500 -> IO c -- returns the value from the in-between computation
501 bracketOnError before after thing =
506 (\e -> do { after a; throw e })
509 -- -----------------------------------------------------------------------------
510 -- Asynchronous exceptions
514 #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
515 external influences, and can be raised at any point during execution.
516 'StackOverflow' and 'HeapOverflow' are two examples of
517 system-generated asynchronous exceptions.
519 The primary source of asynchronous exceptions, however, is
522 > throwTo :: ThreadId -> Exception -> IO ()
524 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
525 running thread to raise an arbitrary exception in another thread. The
526 exception is therefore asynchronous with respect to the target thread,
527 which could be doing anything at the time it receives the exception.
528 Great care should be taken with asynchronous exceptions; it is all too
529 easy to introduce race conditions by the over zealous use of
534 There\'s an implied 'block' around every exception handler in a call
535 to one of the 'catch' family of functions. This is because that is
536 what you want most of the time - it eliminates a common race condition
537 in starting an exception handler, because there may be no exception
538 handler on the stack to handle another exception if one arrives
539 immediately. If asynchronous exceptions are blocked on entering the
540 handler, though, we have time to install a new exception handler
541 before being interrupted. If this weren\'t the default, one would have
542 to write something like
545 > catch (unblock (...))
549 If you need to unblock asynchronous exceptions again in the exception
550 handler, just use 'unblock' as normal.
552 Note that 'try' and friends /do not/ have a similar default, because
553 there is no exception handler in this case. If you want to use 'try'
554 in an asynchronous-exception-safe way, you will need to use
560 Some operations are /interruptible/, which means that they can receive
561 asynchronous exceptions even in the scope of a 'block'. Any function
562 which may itself block is defined as interruptible; this includes
563 'Control.Concurrent.MVar.takeMVar'
564 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
565 and most operations which perform
566 some I\/O with the outside world. The reason for having
567 interruptible operations is so that we can write things like
571 > catch (unblock (...))
575 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
577 combination could lead to deadlock, because the thread itself would be
578 blocked in a state where it can\'t receive any asynchronous exceptions.
579 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
580 safe in the knowledge that the thread can receive exceptions right up
581 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
582 Similar arguments apply for other interruptible operations like
583 'System.IO.openFile'.
586 #if !(__GLASGOW_HASKELL__ || __NHC__)
587 assert :: Bool -> a -> a
589 assert False _ = throw (AssertionFailed "")
593 #ifdef __GLASGOW_HASKELL__
594 {-# NOINLINE uncaughtExceptionHandler #-}
595 uncaughtExceptionHandler :: IORef (Exception -> IO ())
596 uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler)
598 defaultHandler :: Exception -> IO ()
599 defaultHandler ex = do
600 (hFlush stdout) `catchAny` (\ _ -> return ())
602 Deadlock -> "no threads to run: infinite loop or deadlock?"
604 other -> showsPrec 0 other ""
605 withCString "%s" $ \cfmt ->
606 withCString msg $ \cmsg ->
609 -- don't use errorBelch() directly, because we cannot call varargs functions
611 foreign import ccall unsafe "HsBase.h errorBelch2"
612 errorBelch :: CString -> CString -> IO ()
614 setUncaughtExceptionHandler :: (Exception -> IO ()) -> IO ()
615 setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler
617 getUncaughtExceptionHandler :: IO (Exception -> IO ())
618 getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler