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
53 catchJust, -- :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a
55 -- ** The @handle@ functions
56 handle, -- :: (Exception -> IO a) -> IO a -> IO a
57 handleJust,-- :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
59 -- ** The @try@ functions
60 try, -- :: IO a -> IO (Either Exception a)
61 tryJust, -- :: (Exception -> Maybe b) -> a -> IO (Either b a)
63 -- ** The @evaluate@ function
64 evaluate, -- :: a -> IO a
66 -- ** The @mapException@ function
67 mapException, -- :: (Exception -> Exception) -> a -> a
69 -- ** Exception predicates
73 ioErrors, -- :: Exception -> Maybe IOError
74 arithExceptions, -- :: Exception -> Maybe ArithException
75 errorCalls, -- :: Exception -> Maybe String
76 dynExceptions, -- :: Exception -> Maybe Dynamic
77 assertions, -- :: Exception -> Maybe String
78 asyncExceptions, -- :: Exception -> Maybe AsyncException
79 userErrors, -- :: Exception -> Maybe String
81 -- * Dynamic exceptions
84 throwDyn, -- :: Typeable ex => ex -> b
85 #ifdef __GLASGOW_HASKELL__
86 throwDynTo, -- :: Typeable ex => ThreadId -> ex -> b
88 catchDyn, -- :: Typeable ex => IO a -> (ex -> IO a) -> IO a
90 -- * Asynchronous Exceptions
94 -- ** Asynchronous exception control
96 -- |The following two functions allow a thread to control delivery of
97 -- asynchronous exceptions during a critical region.
99 block, -- :: IO a -> IO a
100 unblock, -- :: IO a -> IO a
101 blocked, -- :: IO Bool
103 -- *** Applying @block@ to an exception handler
107 -- *** Interruptible operations
113 assert, -- :: Bool -> a -> a
117 bracket, -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO ()
118 bracket_, -- :: IO a -> IO b -> IO c -> IO ()
121 finally, -- :: IO a -> IO b -> IO a
123 #ifdef __GLASGOW_HASKELL__
124 setUncaughtExceptionHandler, -- :: (Exception -> IO ()) -> IO ()
125 getUncaughtExceptionHandler -- :: IO (Exception -> IO ())
129 #ifdef __GLASGOW_HASKELL__
130 import GHC.Base ( assert )
131 import GHC.Exception as ExceptionBase hiding (catch)
132 import GHC.Conc ( throwTo, ThreadId )
133 import Data.IORef ( IORef, newIORef, readIORef, writeIORef )
134 import Foreign.C.String ( CString, withCString )
135 import System.IO ( stdout, hFlush )
139 import Hugs.Exception as ExceptionBase
142 import Prelude hiding ( catch )
143 import System.IO.Error hiding ( catch, try )
144 import System.IO.Unsafe (unsafePerformIO)
148 import qualified System.IO.Error as H'98 (catch)
149 import System.IO.Error (ioError)
151 import DIOError -- defn of IOError type
152 import System (ExitCode())
154 -- minimum needed for nhc98 to pretend it has Exceptions
155 data Exception = IOException IOException
156 | ArithException ArithException
157 | ArrayException ArrayException
158 | AsyncException AsyncException
159 | ExitException ExitCode
160 type IOException = IOError
165 catch :: IO a -> (Exception -> IO a) -> IO a
166 a `catch` b = a `H'98.catch` (b . IOException)
168 throwIO :: Exception -> IO a
169 throwIO (IOException e) = ioError e
170 throwIO _ = ioError (UserError "Control.Exception.throwIO"
172 throw :: Exception -> a
173 throw = unsafePerformIO . throwIO
175 evaluate :: a -> IO a
176 evaluate x = x `seq` return x
178 ioErrors :: Exception -> Maybe IOError
179 ioErrors (IOException e) = Just e
181 arithExceptions :: Exception -> Maybe ArithException
182 arithExceptions (ArithException e) = Just e
183 arithExceptions _ = Nothing
184 errorCalls :: Exception -> Maybe String
185 errorCalls = const Nothing
186 dynExceptions :: Exception -> Maybe Dynamic
187 dynExceptions = const Nothing
188 assertions :: Exception -> Maybe String
189 assertions = const Nothing
190 asyncExceptions :: Exception -> Maybe AsyncException
191 asyncExceptions = const Nothing
192 userErrors :: Exception -> Maybe String
193 userErrors (IOException (UserError _ s)) = Just s
194 userErrors _ = Nothing
196 assert :: Bool -> a -> a
198 assert False _ = throw (IOException (UserError "" "Assertion failed"))
201 #ifndef __GLASGOW_HASKELL__
202 -- Dummy definitions for implementations lacking asynchonous exceptions
204 block :: IO a -> IO a
206 unblock :: IO a -> IO a
209 blocked = return False
212 -----------------------------------------------------------------------------
213 -- Catching exceptions
215 -- |This is the simplest of the exception-catching functions. It
216 -- takes a single argument, runs it, and if an exception is raised
217 -- the \"handler\" is executed, with the value of the exception passed as an
218 -- argument. Otherwise, the result is returned as normal. For example:
220 -- > catch (openFile f ReadMode)
221 -- > (\e -> hPutStr stderr ("Couldn't open "++f++": " ++ show e))
223 -- For catching exceptions in pure (non-'IO') expressions, see the
224 -- function 'evaluate'.
226 -- Note that due to Haskell\'s unspecified evaluation order, an
227 -- expression may return one of several possible exceptions: consider
228 -- the expression @error \"urk\" + 1 \`div\` 0@. Does
229 -- 'catch' execute the handler passing
230 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
232 -- The answer is \"either\": 'catch' makes a
233 -- non-deterministic choice about which exception to catch. If you
234 -- call it again, you might get a different exception back. This is
235 -- ok, because 'catch' is an 'IO' computation.
237 -- Note that 'catch' catches all types of exceptions, and is generally
238 -- used for \"cleaning up\" before passing on the exception using
239 -- 'throwIO'. It is not good practice to discard the exception and
240 -- continue, without first checking the type of the exception (it
241 -- might be a 'ThreadKilled', for example). In this case it is usually better
242 -- to use 'catchJust' and select the kinds of exceptions to catch.
244 -- Also note that the "Prelude" also exports a function called
245 -- 'Prelude.catch' with a similar type to 'Control.Exception.catch',
246 -- except that the "Prelude" version only catches the IO and user
247 -- families of exceptions (as required by Haskell 98).
249 -- We recommend either hiding the "Prelude" version of 'Prelude.catch'
250 -- when importing "Control.Exception":
252 -- > import Prelude hiding (catch)
254 -- or importing "Control.Exception" qualified, to avoid name-clashes:
256 -- > import qualified Control.Exception as C
258 -- and then using @C.catch@
261 catch :: IO a -- ^ The computation to run
262 -> (Exception -> IO a) -- ^ Handler to invoke if an exception is raised
264 catch = ExceptionBase.catchException
266 -- | The function 'catchJust' is like 'catch', but it takes an extra
267 -- argument which is an /exception predicate/, a function which
268 -- selects which type of exceptions we\'re interested in. There are
269 -- some predefined exception predicates for useful subsets of
270 -- exceptions: 'ioErrors', 'arithExceptions', and so on. For example,
271 -- to catch just calls to the 'error' function, we could use
273 -- > result <- catchJust errorCalls thing_to_try handler
275 -- Any other exceptions which are not matched by the predicate
276 -- are re-raised, and may be caught by an enclosing
277 -- 'catch' or 'catchJust'.
279 :: (Exception -> Maybe b) -- ^ Predicate to select exceptions
280 -> IO a -- ^ Computation to run
281 -> (b -> IO a) -- ^ Handler
283 catchJust p a handler = catch a handler'
284 where handler' e = case p e of
288 -- | A version of 'catch' with the arguments swapped around; useful in
289 -- situations where the code for the handler is shorter. For example:
291 -- > do handle (\e -> exitWith (ExitFailure 1)) $
293 handle :: (Exception -> IO a) -> IO a -> IO a
296 -- | A version of 'catchJust' with the arguments swapped around (see
298 handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
299 handleJust p = flip (catchJust p)
301 -----------------------------------------------------------------------------
304 -- | This function maps one exception into another as proposed in the
305 -- paper \"A semantics for imprecise exceptions\".
307 -- Notice that the usage of 'unsafePerformIO' is safe here.
309 mapException :: (Exception -> Exception) -> a -> a
310 mapException f v = unsafePerformIO (catch (evaluate v)
313 -----------------------------------------------------------------------------
314 -- 'try' and variations.
316 -- | Similar to 'catch', but returns an 'Either' result which is
317 -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an
318 -- exception was raised and its value is @e@.
320 -- > try a = catch (Right `liftM` a) (return . Left)
322 -- Note: as with 'catch', it is only polite to use this variant if you intend
323 -- to re-throw the exception after performing whatever cleanup is needed.
324 -- Otherwise, 'tryJust' is generally considered to be better.
326 -- Also note that "System.IO.Error" also exports a function called
327 -- 'System.IO.Error.try' with a similar type to 'Control.Exception.try',
328 -- except that it catches only the IO and user families of exceptions
329 -- (as required by the Haskell 98 @IO@ module).
331 try :: IO a -> IO (Either Exception a)
332 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
334 -- | A variant of 'try' that takes an exception predicate to select
335 -- which exceptions are caught (c.f. 'catchJust'). If the exception
336 -- does not match the predicate, it is re-thrown.
337 tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a)
341 Right v -> return (Right v)
342 Left e -> case p e of
344 Just b -> return (Left b)
346 -----------------------------------------------------------------------------
347 -- Dynamic exceptions
350 -- #DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an
351 -- interface for throwing and catching exceptions of type 'Dynamic'
352 -- (see "Data.Dynamic") which allows exception values of any type in
353 -- the 'Typeable' class to be thrown and caught.
355 -- | Raise any value as an exception, provided it is in the
357 throwDyn :: Typeable exception => exception -> b
359 throwDyn exception = throw (IOException (UserError "" "dynamic exception"))
361 throwDyn exception = throw (DynException (toDyn exception))
364 #ifdef __GLASGOW_HASKELL__
365 -- | A variant of 'throwDyn' that throws the dynamic exception to an
366 -- arbitrary thread (GHC only: c.f. 'throwTo').
367 throwDynTo :: Typeable exception => ThreadId -> exception -> IO ()
368 throwDynTo t exception = throwTo t (DynException (toDyn exception))
369 #endif /* __GLASGOW_HASKELL__ */
371 -- | Catch dynamic exceptions of the required type. All other
372 -- exceptions are re-thrown, including dynamic exceptions of the wrong
375 -- When using dynamic exceptions it is advisable to define a new
376 -- datatype to use for your exception type, to avoid possible clashes
377 -- with dynamic exceptions used in other libraries.
379 catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a
381 catchDyn m k = m -- can't catch dyn exceptions in nhc98
383 catchDyn m k = catchException m handle
384 where handle ex = case ex of
385 (DynException dyn) ->
386 case fromDynamic dyn of
387 Just exception -> k exception
392 -----------------------------------------------------------------------------
393 -- Exception Predicates
396 -- These pre-defined predicates may be used as the first argument to
397 -- 'catchJust', 'tryJust', or 'handleJust' to select certain common
398 -- classes of exceptions.
400 ioErrors :: Exception -> Maybe IOError
401 arithExceptions :: Exception -> Maybe ArithException
402 errorCalls :: Exception -> Maybe String
403 assertions :: Exception -> Maybe String
404 dynExceptions :: Exception -> Maybe Dynamic
405 asyncExceptions :: Exception -> Maybe AsyncException
406 userErrors :: Exception -> Maybe String
408 ioErrors (IOException e) = Just e
411 arithExceptions (ArithException e) = Just e
412 arithExceptions _ = Nothing
414 errorCalls (ErrorCall e) = Just e
415 errorCalls _ = Nothing
417 assertions (AssertionFailed e) = Just e
418 assertions _ = Nothing
420 dynExceptions (DynException e) = Just e
421 dynExceptions _ = Nothing
423 asyncExceptions (AsyncException e) = Just e
424 asyncExceptions _ = Nothing
426 userErrors (IOException e) | isUserError e = Just (ioeGetErrorString e)
427 userErrors _ = Nothing
429 -----------------------------------------------------------------------------
430 -- Some Useful Functions
432 -- | When you want to acquire a resource, do some work with it, and
433 -- then release the resource, it is a good idea to use 'bracket',
434 -- because 'bracket' will install the necessary exception handler to
435 -- release the resource in the event that an exception is raised
436 -- during the computation. If an exception is raised, then 'bracket' will
437 -- re-raise the exception (after performing the release).
439 -- A common example is opening a file:
442 -- > (openFile "filename" ReadMode)
444 -- > (\handle -> do { ... })
446 -- The arguments to 'bracket' are in this order so that we can partially apply
449 -- > withFile name mode = bracket (openFile name mode) hClose
453 :: IO a -- ^ computation to run first (\"acquire resource\")
454 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
455 -> (a -> IO c) -- ^ computation to run in-between
456 -> IO c -- returns the value from the in-between computation
457 bracket before after thing =
462 (\e -> do { after a; throw e })
468 -- | A specialised variant of 'bracket' with just a computation to run
471 finally :: IO a -- ^ computation to run first
472 -> IO b -- ^ computation to run afterward (even if an exception
474 -> IO a -- returns the value from the first computation
479 (\e -> do { sequel; throw e })
484 -- | A variant of 'bracket' where the return value from the first computation
486 bracket_ :: IO a -> IO b -> IO c -> IO c
487 bracket_ before after thing = bracket before (const after) (const thing)
489 -- | Like bracket, but only performs the final action if there was an
490 -- exception raised by the in-between computation.
492 :: IO a -- ^ computation to run first (\"acquire resource\")
493 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
494 -> (a -> IO c) -- ^ computation to run in-between
495 -> IO c -- returns the value from the in-between computation
496 bracketOnError before after thing =
501 (\e -> do { after a; throw e })
504 -- -----------------------------------------------------------------------------
505 -- Asynchronous exceptions
509 #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
510 external influences, and can be raised at any point during execution.
511 'StackOverflow' and 'HeapOverflow' are two examples of
512 system-generated asynchronous exceptions.
514 The primary source of asynchronous exceptions, however, is
517 > throwTo :: ThreadId -> Exception -> IO ()
519 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
520 running thread to raise an arbitrary exception in another thread. The
521 exception is therefore asynchronous with respect to the target thread,
522 which could be doing anything at the time it receives the exception.
523 Great care should be taken with asynchronous exceptions; it is all too
524 easy to introduce race conditions by the over zealous use of
529 There\'s an implied 'block' around every exception handler in a call
530 to one of the 'catch' family of functions. This is because that is
531 what you want most of the time - it eliminates a common race condition
532 in starting an exception handler, because there may be no exception
533 handler on the stack to handle another exception if one arrives
534 immediately. If asynchronous exceptions are blocked on entering the
535 handler, though, we have time to install a new exception handler
536 before being interrupted. If this weren\'t the default, one would have
537 to write something like
540 > catch (unblock (...))
544 If you need to unblock asynchronous exceptions again in the exception
545 handler, just use 'unblock' as normal.
547 Note that 'try' and friends /do not/ have a similar default, because
548 there is no exception handler in this case. If you want to use 'try'
549 in an asynchronous-exception-safe way, you will need to use
555 Some operations are /interruptible/, which means that they can receive
556 asynchronous exceptions even in the scope of a 'block'. Any function
557 which may itself block is defined as interruptible; this includes
558 'Control.Concurrent.MVar.takeMVar'
559 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
560 and most operations which perform
561 some I\/O with the outside world. The reason for having
562 interruptible operations is so that we can write things like
566 > catch (unblock (...))
570 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
572 combination could lead to deadlock, because the thread itself would be
573 blocked in a state where it can\'t receive any asynchronous exceptions.
574 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
575 safe in the knowledge that the thread can receive exceptions right up
576 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
577 Similar arguments apply for other interruptible operations like
578 'System.IO.openFile'.
581 #if !(__GLASGOW_HASKELL__ || __NHC__)
582 assert :: Bool -> a -> a
584 assert False _ = throw (AssertionFailed "")
588 #ifdef __GLASGOW_HASKELL__
589 {-# NOINLINE uncaughtExceptionHandler #-}
590 uncaughtExceptionHandler :: IORef (Exception -> IO ())
591 uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler)
593 defaultHandler :: Exception -> IO ()
594 defaultHandler ex = do
595 (hFlush stdout) `catchException` (\ _ -> return ())
597 Deadlock -> "no threads to run: infinite loop or deadlock?"
599 other -> showsPrec 0 other ""
600 withCString "%s" $ \cfmt ->
601 withCString msg $ \cmsg ->
604 -- don't use errorBelch() directly, because we cannot call varargs functions
606 foreign import ccall unsafe "HsBase.h errorBelch2"
607 errorBelch :: CString -> CString -> IO ()
609 setUncaughtExceptionHandler :: (Exception -> IO ()) -> IO ()
610 setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler
612 getUncaughtExceptionHandler :: IO (Exception -> IO ())
613 getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler