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
102 -- *** Applying @block@ to an exception handler
106 -- *** Interruptible operations
112 assert, -- :: Bool -> a -> a
116 bracket, -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO ()
117 bracket_, -- :: IO a -> IO b -> IO c -> IO ()
120 finally, -- :: IO a -> IO b -> IO a
122 #ifdef __GLASGOW_HASKELL__
123 setUncaughtExceptionHandler, -- :: (Exception -> IO ()) -> IO ()
124 getUncaughtExceptionHandler -- :: IO (Exception -> IO ())
128 #ifdef __GLASGOW_HASKELL__
129 import GHC.Base ( assert )
130 import GHC.Exception as ExceptionBase hiding (catch)
131 import GHC.Conc ( throwTo, ThreadId )
132 import Data.IORef ( IORef, newIORef, readIORef, writeIORef )
133 import Foreign.C.String ( CString, withCString )
134 import System.IO ( stdout, hFlush )
138 import Hugs.Exception as ExceptionBase
141 import Prelude hiding ( catch )
142 import System.IO.Error hiding ( catch, try )
143 import System.IO.Unsafe (unsafePerformIO)
147 import System.IO.Error (catch, ioError)
149 import DIOError -- defn of IOError type
151 -- minimum needed for nhc98 to pretend it has Exceptions
152 type Exception = IOError
153 type IOException = IOError
158 throwIO :: Exception -> IO a
160 throw :: Exception -> a
161 throw = unsafePerformIO . throwIO
163 evaluate :: a -> IO a
164 evaluate x = x `seq` return x
166 ioErrors :: Exception -> Maybe IOError
168 arithExceptions :: Exception -> Maybe ArithException
169 arithExceptions = const Nothing
170 errorCalls :: Exception -> Maybe String
171 errorCalls = const Nothing
172 dynExceptions :: Exception -> Maybe Dynamic
173 dynExceptions = const Nothing
174 assertions :: Exception -> Maybe String
175 assertions = const Nothing
176 asyncExceptions :: Exception -> Maybe AsyncException
177 asyncExceptions = const Nothing
178 userErrors :: Exception -> Maybe String
179 userErrors (UserError _ s) = Just s
180 userErrors _ = Nothing
182 block :: IO a -> IO a
184 unblock :: IO a -> IO a
187 assert :: Bool -> a -> a
189 assert False _ = throw (UserError "" "Assertion failed")
192 -----------------------------------------------------------------------------
193 -- Catching exceptions
195 -- |This is the simplest of the exception-catching functions. It
196 -- takes a single argument, runs it, and if an exception is raised
197 -- the \"handler\" is executed, with the value of the exception passed as an
198 -- argument. Otherwise, the result is returned as normal. For example:
200 -- > catch (openFile f ReadMode)
201 -- > (\e -> hPutStr stderr ("Couldn't open "++f++": " ++ show e))
203 -- For catching exceptions in pure (non-'IO') expressions, see the
204 -- function 'evaluate'.
206 -- Note that due to Haskell\'s unspecified evaluation order, an
207 -- expression may return one of several possible exceptions: consider
208 -- the expression @error \"urk\" + 1 \`div\` 0@. Does
209 -- 'catch' execute the handler passing
210 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
212 -- The answer is \"either\": 'catch' makes a
213 -- non-deterministic choice about which exception to catch. If you
214 -- call it again, you might get a different exception back. This is
215 -- ok, because 'catch' is an 'IO' computation.
217 -- Note that 'catch' catches all types of exceptions, and is generally
218 -- used for \"cleaning up\" before passing on the exception using
219 -- 'throwIO'. It is not good practice to discard the exception and
220 -- continue, without first checking the type of the exception (it
221 -- might be a 'ThreadKilled', for example). In this case it is usually better
222 -- to use 'catchJust' and select the kinds of exceptions to catch.
224 -- Also note that the "Prelude" also exports a function called
225 -- 'Prelude.catch' with a similar type to 'Control.Exception.catch',
226 -- except that the "Prelude" version only catches the IO and user
227 -- families of exceptions (as required by Haskell 98).
229 -- We recommend either hiding the "Prelude" version of 'Prelude.catch'
230 -- when importing "Control.Exception":
232 -- > import Prelude hiding (catch)
234 -- or importing "Control.Exception" qualified, to avoid name-clashes:
236 -- > import qualified Control.Exception as C
238 -- and then using @C.catch@
241 catch :: IO a -- ^ The computation to run
242 -> (Exception -> IO a) -- ^ Handler to invoke if an exception is raised
244 catch = ExceptionBase.catchException
246 -- | The function 'catchJust' is like 'catch', but it takes an extra
247 -- argument which is an /exception predicate/, a function which
248 -- selects which type of exceptions we\'re interested in. There are
249 -- some predefined exception predicates for useful subsets of
250 -- exceptions: 'ioErrors', 'arithExceptions', and so on. For example,
251 -- to catch just calls to the 'error' function, we could use
253 -- > result <- catchJust errorCalls thing_to_try handler
255 -- Any other exceptions which are not matched by the predicate
256 -- are re-raised, and may be caught by an enclosing
257 -- 'catch' or 'catchJust'.
259 :: (Exception -> Maybe b) -- ^ Predicate to select exceptions
260 -> IO a -- ^ Computation to run
261 -> (b -> IO a) -- ^ Handler
263 catchJust p a handler = catch a handler'
264 where handler' e = case p e of
268 -- | A version of 'catch' with the arguments swapped around; useful in
269 -- situations where the code for the handler is shorter. For example:
271 -- > do handle (\e -> exitWith (ExitFailure 1)) $
273 handle :: (Exception -> IO a) -> IO a -> IO a
276 -- | A version of 'catchJust' with the arguments swapped around (see
278 handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
279 handleJust p = flip (catchJust p)
281 -----------------------------------------------------------------------------
284 -- | This function maps one exception into another as proposed in the
285 -- paper \"A semantics for imprecise exceptions\".
287 -- Notice that the usage of 'unsafePerformIO' is safe here.
289 mapException :: (Exception -> Exception) -> a -> a
290 mapException f v = unsafePerformIO (catch (evaluate v)
293 -----------------------------------------------------------------------------
294 -- 'try' and variations.
296 -- | Similar to 'catch', but returns an 'Either' result which is
297 -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an
298 -- exception was raised and its value is @e@.
300 -- > try a = catch (Right `liftM` a) (return . Left)
302 -- Note: as with 'catch', it is only polite to use this variant if you intend
303 -- to re-throw the exception after performing whatever cleanup is needed.
304 -- Otherwise, 'tryJust' is generally considered to be better.
306 -- Also note that "System.IO.Error" also exports a function called
307 -- 'System.IO.Error.try' with a similar type to 'Control.Exception.try',
308 -- except that it catches only the IO and user families of exceptions
309 -- (as required by the Haskell 98 @IO@ module).
311 try :: IO a -> IO (Either Exception a)
312 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
314 -- | A variant of 'try' that takes an exception predicate to select
315 -- which exceptions are caught (c.f. 'catchJust'). If the exception
316 -- does not match the predicate, it is re-thrown.
317 tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a)
321 Right v -> return (Right v)
322 Left e -> case p e of
324 Just b -> return (Left b)
326 -----------------------------------------------------------------------------
327 -- Dynamic exceptions
330 -- #DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an
331 -- interface for throwing and catching exceptions of type 'Dynamic'
332 -- (see "Data.Dynamic") which allows exception values of any type in
333 -- the 'Typeable' class to be thrown and caught.
335 -- | Raise any value as an exception, provided it is in the
337 throwDyn :: Typeable exception => exception -> b
339 throwDyn exception = throw (UserError "" "dynamic exception")
341 throwDyn exception = throw (DynException (toDyn exception))
344 #ifdef __GLASGOW_HASKELL__
345 -- | A variant of 'throwDyn' that throws the dynamic exception to an
346 -- arbitrary thread (GHC only: c.f. 'throwTo').
347 throwDynTo :: Typeable exception => ThreadId -> exception -> IO ()
348 throwDynTo t exception = throwTo t (DynException (toDyn exception))
349 #endif /* __GLASGOW_HASKELL__ */
351 -- | Catch dynamic exceptions of the required type. All other
352 -- exceptions are re-thrown, including dynamic exceptions of the wrong
355 -- When using dynamic exceptions it is advisable to define a new
356 -- datatype to use for your exception type, to avoid possible clashes
357 -- with dynamic exceptions used in other libraries.
359 catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a
361 catchDyn m k = m -- can't catch dyn exceptions in nhc98
363 catchDyn m k = catchException m handle
364 where handle ex = case ex of
365 (DynException dyn) ->
366 case fromDynamic dyn of
367 Just exception -> k exception
372 -----------------------------------------------------------------------------
373 -- Exception Predicates
376 -- These pre-defined predicates may be used as the first argument to
377 -- 'catchJust', 'tryJust', or 'handleJust' to select certain common
378 -- classes of exceptions.
380 ioErrors :: Exception -> Maybe IOError
381 arithExceptions :: Exception -> Maybe ArithException
382 errorCalls :: Exception -> Maybe String
383 assertions :: Exception -> Maybe String
384 dynExceptions :: Exception -> Maybe Dynamic
385 asyncExceptions :: Exception -> Maybe AsyncException
386 userErrors :: Exception -> Maybe String
388 ioErrors (IOException e) = Just e
391 arithExceptions (ArithException e) = Just e
392 arithExceptions _ = Nothing
394 errorCalls (ErrorCall e) = Just e
395 errorCalls _ = Nothing
397 assertions (AssertionFailed e) = Just e
398 assertions _ = Nothing
400 dynExceptions (DynException e) = Just e
401 dynExceptions _ = Nothing
403 asyncExceptions (AsyncException e) = Just e
404 asyncExceptions _ = Nothing
406 userErrors (IOException e) | isUserError e = Just (ioeGetErrorString e)
407 userErrors _ = Nothing
409 -----------------------------------------------------------------------------
410 -- Some Useful Functions
412 -- | When you want to acquire a resource, do some work with it, and
413 -- then release the resource, it is a good idea to use 'bracket',
414 -- because 'bracket' will install the necessary exception handler to
415 -- release the resource in the event that an exception is raised
416 -- during the computation. If an exception is raised, then 'bracket' will
417 -- re-raise the exception (after performing the release).
419 -- A common example is opening a file:
422 -- > (openFile "filename" ReadMode)
424 -- > (\handle -> do { ... })
426 -- The arguments to 'bracket' are in this order so that we can partially apply
429 -- > withFile name mode = bracket (openFile name mode) hClose
433 :: IO a -- ^ computation to run first (\"acquire resource\")
434 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
435 -> (a -> IO c) -- ^ computation to run in-between
436 -> IO c -- returns the value from the in-between computation
437 bracket before after thing =
442 (\e -> do { after a; throw e })
448 -- | A specialised variant of 'bracket' with just a computation to run
451 finally :: IO a -- ^ computation to run first
452 -> IO b -- ^ computation to run afterward (even if an exception
454 -> IO a -- returns the value from the first computation
459 (\e -> do { sequel; throw e })
464 -- | A variant of 'bracket' where the return value from the first computation
466 bracket_ :: IO a -> IO b -> IO c -> IO c
467 bracket_ before after thing = bracket before (const after) (const thing)
469 -- | Like bracket, but only performs the final action if there was an
470 -- exception raised by the in-between computation.
472 :: IO a -- ^ computation to run first (\"acquire resource\")
473 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
474 -> (a -> IO c) -- ^ computation to run in-between
475 -> IO c -- returns the value from the in-between computation
476 bracketOnError before after thing =
481 (\e -> do { after a; throw e })
484 -- -----------------------------------------------------------------------------
485 -- Asynchronous exceptions
489 #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
490 external influences, and can be raised at any point during execution.
491 'StackOverflow' and 'HeapOverflow' are two examples of
492 system-generated asynchronous exceptions.
494 The primary source of asynchronous exceptions, however, is
497 > throwTo :: ThreadId -> Exception -> IO ()
499 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
500 running thread to raise an arbitrary exception in another thread. The
501 exception is therefore asynchronous with respect to the target thread,
502 which could be doing anything at the time it receives the exception.
503 Great care should be taken with asynchronous exceptions; it is all too
504 easy to introduce race conditions by the over zealous use of
509 There\'s an implied 'block' around every exception handler in a call
510 to one of the 'catch' family of functions. This is because that is
511 what you want most of the time - it eliminates a common race condition
512 in starting an exception handler, because there may be no exception
513 handler on the stack to handle another exception if one arrives
514 immediately. If asynchronous exceptions are blocked on entering the
515 handler, though, we have time to install a new exception handler
516 before being interrupted. If this weren\'t the default, one would have
517 to write something like
520 > catch (unblock (...))
524 If you need to unblock asynchronous exceptions again in the exception
525 handler, just use 'unblock' as normal.
527 Note that 'try' and friends /do not/ have a similar default, because
528 there is no exception handler in this case. If you want to use 'try'
529 in an asynchronous-exception-safe way, you will need to use
535 Some operations are /interruptible/, which means that they can receive
536 asynchronous exceptions even in the scope of a 'block'. Any function
537 which may itself block is defined as interruptible; this includes
538 'Control.Concurrent.MVar.takeMVar'
539 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
540 and most operations which perform
541 some I\/O with the outside world. The reason for having
542 interruptible operations is so that we can write things like
546 > catch (unblock (...))
550 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
552 combination could lead to deadlock, because the thread itself would be
553 blocked in a state where it can\'t receive any asynchronous exceptions.
554 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
555 safe in the knowledge that the thread can receive exceptions right up
556 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
557 Similar arguments apply for other interruptible operations like
558 'System.IO.openFile'.
561 #if !(__GLASGOW_HASKELL__ || __NHC__)
562 assert :: Bool -> a -> a
564 assert False _ = throw (AssertionFailed "")
568 #ifdef __GLASGOW_HASKELL__
569 {-# NOINLINE uncaughtExceptionHandler #-}
570 uncaughtExceptionHandler :: IORef (Exception -> IO ())
571 uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler)
573 defaultHandler :: Exception -> IO ()
574 defaultHandler ex = do
575 (hFlush stdout) `catchException` (\ _ -> return ())
577 Deadlock -> "no threads to run: infinite loop or deadlock?"
579 other -> showsPrec 0 other ""
580 withCString "%s" $ \cfmt ->
581 withCString msg $ \cmsg ->
584 foreign import ccall unsafe "RtsMessages.h errorBelch"
585 errorBelch :: CString -> CString -> IO ()
587 setUncaughtExceptionHandler :: (Exception -> IO ()) -> IO ()
588 setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler
590 getUncaughtExceptionHandler :: IO (Exception -> IO ())
591 getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler