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)
146 -----------------------------------------------------------------------------
147 -- Catching exceptions
149 -- |This is the simplest of the exception-catching functions. It
150 -- takes a single argument, runs it, and if an exception is raised
151 -- the \"handler\" is executed, with the value of the exception passed as an
152 -- argument. Otherwise, the result is returned as normal. For example:
154 -- > catch (openFile f ReadMode)
155 -- > (\e -> hPutStr stderr (\"Couldn\'t open \"++f++\": \" ++ show e))
157 -- For catching exceptions in pure (non-'IO') expressions, see the
158 -- function 'evaluate'.
160 -- Note that due to Haskell\'s unspecified evaluation order, an
161 -- expression may return one of several possible exceptions: consider
162 -- the expression @error \"urk\" + 1 \`div\` 0@. Does
163 -- 'catch' execute the handler passing
164 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
166 -- The answer is \"either\": 'catch' makes a
167 -- non-deterministic choice about which exception to catch. If you
168 -- call it again, you might get a different exception back. This is
169 -- ok, because 'catch' is an 'IO' computation.
171 -- Note that 'catch' catches all types of exceptions, and is generally
172 -- used for \"cleaning up\" before passing on the exception using
173 -- 'throwIO'. It is not good practice to discard the exception and
174 -- continue, without first checking the type of the exception (it
175 -- might be a 'ThreadKilled', for example). In this case it is usually better
176 -- to use 'catchJust' and select the kinds of exceptions to catch.
178 -- Also note that the "Prelude" also exports a function called
179 -- 'Prelude.catch' with a similar type to 'Control.Exception.catch',
180 -- except that the "Prelude" version only catches the IO and user
181 -- families of exceptions (as required by Haskell 98). We recommend
182 -- either hiding the "Prelude" version of
183 -- 'Prelude.catch' when importing
184 -- "Control.Exception", or importing
185 -- "Control.Exception" qualified, to avoid name-clashes.
187 catch :: IO a -- ^ The computation to run
188 -> (Exception -> IO a) -- ^ Handler to invoke if an exception is raised
190 catch = ExceptionBase.catchException
192 -- | The function 'catchJust' is like 'catch', but it takes an extra
193 -- argument which is an /exception predicate/, a function which
194 -- selects which type of exceptions we\'re interested in. There are
195 -- some predefined exception predicates for useful subsets of
196 -- exceptions: 'ioErrors', 'arithExceptions', and so on. For example,
197 -- to catch just calls to the 'error' function, we could use
199 -- > result <- catchJust errorCalls thing_to_try handler
201 -- Any other exceptions which are not matched by the predicate
202 -- are re-raised, and may be caught by an enclosing
203 -- 'catch' or 'catchJust'.
205 :: (Exception -> Maybe b) -- ^ Predicate to select exceptions
206 -> IO a -- ^ Computation to run
207 -> (b -> IO a) -- ^ Handler
209 catchJust p a handler = catch a handler'
210 where handler' e = case p e of
214 -- | A version of 'catch' with the arguments swapped around; useful in
215 -- situations where the code for the handler is shorter. For example:
217 -- > do handle (\e -> exitWith (ExitFailure 1)) $
219 handle :: (Exception -> IO a) -> IO a -> IO a
222 -- | A version of 'catchJust' with the arguments swapped around (see
224 handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
225 handleJust p = flip (catchJust p)
227 -----------------------------------------------------------------------------
230 -- | This function maps one exception into another as proposed in the
231 -- paper \"A semantics for imprecise exceptions\".
233 -- Notice that the usage of 'unsafePerformIO' is safe here.
235 mapException :: (Exception -> Exception) -> a -> a
236 mapException f v = unsafePerformIO (catch (evaluate v)
239 -----------------------------------------------------------------------------
240 -- 'try' and variations.
242 -- | Similar to 'catch', but returns an 'Either' result which is
243 -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an
244 -- exception was raised and its value is @e@.
246 -- > try a = catch (Right \`liftM\` a) (return . Left)
248 -- Note: as with 'catch', it is only polite to use this variant if you intend
249 -- to re-throw the exception after performing whatever cleanup is needed.
250 -- Otherwise, 'tryJust' is generally considered to be better.
252 -- Also note that "System.IO.Error" also exports a function called
253 -- 'System.IO.Error.try' with a similar type to 'Control.Exception.try',
254 -- except that it catches only the IO and user families of exceptions
255 -- (as required by the Haskell 98 @IO@ module).
257 try :: IO a -> IO (Either Exception a)
258 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
260 -- | A variant of 'try' that takes an exception predicate to select
261 -- which exceptions are caught (c.f. 'catchJust'). If the exception
262 -- does not match the predicate, it is re-thrown.
263 tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a)
267 Right v -> return (Right v)
268 Left e -> case p e of
270 Just b -> return (Left b)
272 -----------------------------------------------------------------------------
273 -- Dynamic exceptions
276 -- #DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an
277 -- interface for throwing and catching exceptions of type 'Dynamic'
278 -- (see "Data.Dynamic") which allows exception values of any type in
279 -- the 'Typeable' class to be thrown and caught.
281 -- | Raise any value as an exception, provided it is in the
283 throwDyn :: Typeable exception => exception -> b
284 throwDyn exception = throw (DynException (toDyn exception))
286 #ifdef __GLASGOW_HASKELL__
287 -- | A variant of 'throwDyn' that throws the dynamic exception to an
288 -- arbitrary thread (GHC only: c.f. 'throwTo').
289 throwDynTo :: Typeable exception => ThreadId -> exception -> IO ()
290 throwDynTo t exception = throwTo t (DynException (toDyn exception))
291 #endif /* __GLASGOW_HASKELL__ */
293 -- | Catch dynamic exceptions of the required type. All other
294 -- exceptions are re-thrown, including dynamic exceptions of the wrong
297 -- When using dynamic exceptions it is advisable to define a new
298 -- datatype to use for your exception type, to avoid possible clashes
299 -- with dynamic exceptions used in other libraries.
301 catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a
302 catchDyn m k = catchException m handle
303 where handle ex = case ex of
304 (DynException dyn) ->
305 case fromDynamic dyn of
306 Just exception -> k exception
310 -----------------------------------------------------------------------------
311 -- Exception Predicates
314 -- These pre-defined predicates may be used as the first argument to
315 -- 'catchJust', 'tryJust', or 'handleJust' to select certain common
316 -- classes of exceptions.
318 ioErrors :: Exception -> Maybe IOError
319 arithExceptions :: Exception -> Maybe ArithException
320 errorCalls :: Exception -> Maybe String
321 assertions :: Exception -> Maybe String
322 dynExceptions :: Exception -> Maybe Dynamic
323 asyncExceptions :: Exception -> Maybe AsyncException
324 userErrors :: Exception -> Maybe String
326 ioErrors (IOException e) = Just e
329 arithExceptions (ArithException e) = Just e
330 arithExceptions _ = Nothing
332 errorCalls (ErrorCall e) = Just e
333 errorCalls _ = Nothing
335 assertions (AssertionFailed e) = Just e
336 assertions _ = Nothing
338 dynExceptions (DynException e) = Just e
339 dynExceptions _ = Nothing
341 asyncExceptions (AsyncException e) = Just e
342 asyncExceptions _ = Nothing
344 userErrors (IOException e) | isUserError e = Just (ioeGetErrorString e)
345 userErrors _ = Nothing
347 -----------------------------------------------------------------------------
348 -- Some Useful Functions
350 -- | When you want to acquire a resource, do some work with it, and
351 -- then release the resource, it is a good idea to use 'bracket',
352 -- because 'bracket' will install the necessary exception handler to
353 -- release the resource in the event that an exception is raised
354 -- during the computation. If an exception is raised, then 'bracket' will
355 -- re-raise the exception (after performing the release).
357 -- A common example is opening a file:
360 -- > (openFile "filename" ReadMode)
362 -- > (\handle -> do { ... })
364 -- The arguments to 'bracket' are in this order so that we can partially apply
367 -- > withFile name = bracket (openFile name) hClose
370 :: IO a -- ^ computation to run first (\"acquire resource\")
371 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
372 -> (a -> IO c) -- ^ computation to run in-between
373 -> IO c -- returns the value from the in-between computation
374 bracket before after thing =
379 (\e -> do { after a; throw e })
385 -- | A specialised variant of 'bracket' with just a computation to run
388 finally :: IO a -- ^ computation to run first
389 -> IO b -- ^ computation to run afterward (even if an exception
391 -> IO a -- returns the value from the first computation
396 (\e -> do { sequel; throw e })
401 -- | A variant of 'bracket' where the return value from the first computation
403 bracket_ :: IO a -> IO b -> IO c -> IO c
404 bracket_ before after thing = bracket before (const after) (const thing)
406 -- | Like bracket, but only performs the final action if there was an
407 -- exception raised by the in-between computation.
409 :: IO a -- ^ computation to run first (\"acquire resource\")
410 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
411 -> (a -> IO c) -- ^ computation to run in-between
412 -> IO c -- returns the value from the in-between computation
413 bracketOnError before after thing =
418 (\e -> do { after a; throw e })
421 -- -----------------------------------------------------------------------------
422 -- Asynchronous exceptions
426 #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
427 external influences, and can be raised at any point during execution.
428 'StackOverflow' and 'HeapOverflow' are two examples of
429 system-generated asynchronous exceptions.
431 The primary source of asynchronous exceptions, however, is
434 > throwTo :: ThreadId -> Exception -> IO ()
436 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
437 running thread to raise an arbitrary exception in another thread. The
438 exception is therefore asynchronous with respect to the target thread,
439 which could be doing anything at the time it receives the exception.
440 Great care should be taken with asynchronous exceptions; it is all too
441 easy to introduce race conditions by the over zealous use of
446 There\'s an implied 'block' around every exception handler in a call
447 to one of the 'catch' family of functions. This is because that is
448 what you want most of the time - it eliminates a common race condition
449 in starting an exception handler, because there may be no exception
450 handler on the stack to handle another exception if one arrives
451 immediately. If asynchronous exceptions are blocked on entering the
452 handler, though, we have time to install a new exception handler
453 before being interrupted. If this weren\'t the default, one would have
454 to write something like
457 > catch (unblock (...))
461 If you need to unblock asynchronous exceptions again in the exception
462 handler, just use 'unblock' as normal.
464 Note that 'try' and friends /do not/ have a similar default, because
465 there is no exception handler in this case. If you want to use 'try'
466 in an asynchronous-exception-safe way, you will need to use
472 Some operations are /interruptible/, which means that they can receive
473 asynchronous exceptions even in the scope of a 'block'. Any function
474 which may itself block is defined as interruptible; this includes
475 'Control.Concurrent.MVar.takeMVar'
476 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
477 and most operations which perform
478 some I\/O with the outside world. The reason for having
479 interruptible operations is so that we can write things like
483 > catch (unblock (...))
487 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
489 combination could lead to deadlock, because the thread itself would be
490 blocked in a state where it can\'t receive any asynchronous exceptions.
491 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
492 safe in the knowledge that the thread can receive exceptions right up
493 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
494 Similar arguments apply for other interruptible operations like
495 'System.IO.openFile'.
498 #ifndef __GLASGOW_HASKELL__
499 assert :: Bool -> a -> a
501 assert False _ = throw (AssertionFailed "")
505 #ifdef __GLASGOW_HASKELL__
506 {-# NOINLINE uncaughtExceptionHandler #-}
507 uncaughtExceptionHandler :: IORef (Exception -> IO ())
508 uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler)
510 defaultHandler :: Exception -> IO ()
511 defaultHandler ex = do
512 (hFlush stdout) `catchException` (\ _ -> return ())
514 Deadlock -> "no threads to run: infinite loop or deadlock?"
516 other -> showsPrec 0 other "\n"
517 withCString "%s" $ \cfmt ->
518 withCString msg $ \cmsg ->
521 foreign import ccall unsafe "RtsMessages.h errorBelch"
522 errorBelch :: CString -> CString -> IO ()
524 setUncaughtExceptionHandler :: (Exception -> IO ()) -> IO ()
525 setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler
527 getUncaughtExceptionHandler :: IO (Exception -> IO ())
528 getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler