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.Base ( assert )
133 import GHC.Exception as ExceptionBase hiding (Exception, catch)
134 import GHC.Conc ( throwTo, ThreadId )
135 import Data.IORef ( IORef, newIORef, readIORef, writeIORef )
136 import Foreign.C.String ( CString, withCString )
137 import System.IO ( stdout, hFlush )
141 import Hugs.Exception as ExceptionBase
144 import Prelude hiding ( catch )
145 import System.IO.Error hiding ( catch, try )
146 import System.IO.Unsafe (unsafePerformIO)
150 import qualified System.IO.Error as H'98 (catch)
151 import System.IO.Error (ioError)
153 import DIOError -- defn of IOError type
154 import System (ExitCode())
156 -- minimum needed for nhc98 to pretend it has Exceptions
157 data Exception = IOException IOException
158 | ArithException ArithException
159 | ArrayException ArrayException
160 | AsyncException AsyncException
161 | ExitException ExitCode
163 type IOException = IOError
167 instance Show ArithException
168 instance Show ArrayException
169 instance Show AsyncException
171 catch :: IO a -> (Exception -> IO a) -> IO a
172 a `catch` b = a `H'98.catch` (b . IOException)
174 throwIO :: Exception -> IO a
175 throwIO (IOException e) = ioError e
176 throwIO _ = ioError (UserError "Control.Exception.throwIO"
178 throw :: Exception -> a
179 throw = unsafePerformIO . throwIO
181 evaluate :: a -> IO a
182 evaluate x = x `seq` return x
184 ioErrors :: Exception -> Maybe IOError
185 ioErrors (IOException e) = Just e
187 arithExceptions :: Exception -> Maybe ArithException
188 arithExceptions (ArithException e) = Just e
189 arithExceptions _ = Nothing
190 errorCalls :: Exception -> Maybe String
191 errorCalls = const Nothing
192 dynExceptions :: Exception -> Maybe Dynamic
193 dynExceptions = const Nothing
194 assertions :: Exception -> Maybe String
195 assertions = const Nothing
196 asyncExceptions :: Exception -> Maybe AsyncException
197 asyncExceptions = const Nothing
198 userErrors :: Exception -> Maybe String
199 userErrors (IOException (UserError _ s)) = Just s
200 userErrors _ = Nothing
202 assert :: Bool -> a -> a
204 assert False _ = throw (IOException (UserError "" "Assertion failed"))
207 #ifndef __GLASGOW_HASKELL__
208 -- Dummy definitions for implementations lacking asynchonous exceptions
210 block :: IO a -> IO a
212 unblock :: IO a -> IO a
215 blocked = return False
218 -----------------------------------------------------------------------------
219 -- Catching exceptions
221 -- |This is the simplest of the exception-catching functions. It
222 -- takes a single argument, runs it, and if an exception is raised
223 -- the \"handler\" is executed, with the value of the exception passed as an
224 -- argument. Otherwise, the result is returned as normal. For example:
226 -- > catch (openFile f ReadMode)
227 -- > (\e -> hPutStr stderr ("Couldn't open "++f++": " ++ show e))
229 -- For catching exceptions in pure (non-'IO') expressions, see the
230 -- function 'evaluate'.
232 -- Note that due to Haskell\'s unspecified evaluation order, an
233 -- expression may return one of several possible exceptions: consider
234 -- the expression @error \"urk\" + 1 \`div\` 0@. Does
235 -- 'catch' execute the handler passing
236 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
238 -- The answer is \"either\": 'catch' makes a
239 -- non-deterministic choice about which exception to catch. If you
240 -- call it again, you might get a different exception back. This is
241 -- ok, because 'catch' is an 'IO' computation.
243 -- Note that 'catch' catches all types of exceptions, and is generally
244 -- used for \"cleaning up\" before passing on the exception using
245 -- 'throwIO'. It is not good practice to discard the exception and
246 -- continue, without first checking the type of the exception (it
247 -- might be a 'ThreadKilled', for example). In this case it is usually better
248 -- to use 'catchJust' and select the kinds of exceptions to catch.
250 -- Also note that the "Prelude" also exports a function called
251 -- 'Prelude.catch' with a similar type to 'Control.Exception.catch',
252 -- except that the "Prelude" version only catches the IO and user
253 -- families of exceptions (as required by Haskell 98).
255 -- We recommend either hiding the "Prelude" version of 'Prelude.catch'
256 -- when importing "Control.Exception":
258 -- > import Prelude hiding (catch)
260 -- or importing "Control.Exception" qualified, to avoid name-clashes:
262 -- > import qualified Control.Exception as C
264 -- and then using @C.catch@
267 catch :: IO a -- ^ The computation to run
268 -> (Exception -> IO a) -- ^ Handler to invoke if an exception is raised
270 catch = ExceptionBase.catchException
272 -- | The function 'catchJust' is like 'catch', but it takes an extra
273 -- argument which is an /exception predicate/, a function which
274 -- selects which type of exceptions we\'re interested in. There are
275 -- some predefined exception predicates for useful subsets of
276 -- exceptions: 'ioErrors', 'arithExceptions', and so on. For example,
277 -- to catch just calls to the 'error' function, we could use
279 -- > result <- catchJust errorCalls thing_to_try handler
281 -- Any other exceptions which are not matched by the predicate
282 -- are re-raised, and may be caught by an enclosing
283 -- 'catch' or 'catchJust'.
285 :: (Exception -> Maybe b) -- ^ Predicate to select exceptions
286 -> IO a -- ^ Computation to run
287 -> (b -> IO a) -- ^ Handler
289 catchJust p a handler = catch a handler'
290 where handler' e = case p e of
294 -- | A version of 'catch' with the arguments swapped around; useful in
295 -- situations where the code for the handler is shorter. For example:
297 -- > do handle (\e -> exitWith (ExitFailure 1)) $
299 handle :: (Exception -> IO a) -> IO a -> IO a
302 -- | A version of 'catchJust' with the arguments swapped around (see
304 handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
305 handleJust p = flip (catchJust p)
307 -----------------------------------------------------------------------------
310 -- | This function maps one exception into another as proposed in the
311 -- paper \"A semantics for imprecise exceptions\".
313 -- Notice that the usage of 'unsafePerformIO' is safe here.
315 mapException :: (Exception -> Exception) -> a -> a
316 mapException f v = unsafePerformIO (catch (evaluate v)
319 -----------------------------------------------------------------------------
320 -- 'try' and variations.
322 -- | Similar to 'catch', but returns an 'Either' result which is
323 -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an
324 -- exception was raised and its value is @e@.
326 -- > try a = catch (Right `liftM` a) (return . Left)
328 -- Note: as with 'catch', it is only polite to use this variant if you intend
329 -- to re-throw the exception after performing whatever cleanup is needed.
330 -- Otherwise, 'tryJust' is generally considered to be better.
332 -- Also note that "System.IO.Error" also exports a function called
333 -- 'System.IO.Error.try' with a similar type to 'Control.Exception.try',
334 -- except that it catches only the IO and user families of exceptions
335 -- (as required by the Haskell 98 @IO@ module).
337 try :: IO a -> IO (Either Exception a)
338 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
340 -- | A variant of 'try' that takes an exception predicate to select
341 -- which exceptions are caught (c.f. 'catchJust'). If the exception
342 -- does not match the predicate, it is re-thrown.
343 tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a)
347 Right v -> return (Right v)
348 Left e -> case p e of
350 Just b -> return (Left b)
352 -----------------------------------------------------------------------------
353 -- Dynamic exceptions
356 -- #DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an
357 -- interface for throwing and catching exceptions of type 'Dynamic'
358 -- (see "Data.Dynamic") which allows exception values of any type in
359 -- the 'Typeable' class to be thrown and caught.
361 -- | Raise any value as an exception, provided it is in the
363 throwDyn :: Typeable exception => exception -> b
365 throwDyn exception = throw (IOException (UserError "" "dynamic exception"))
367 throwDyn exception = throw (DynException (toDyn exception))
370 #ifdef __GLASGOW_HASKELL__
371 -- | A variant of 'throwDyn' that throws the dynamic exception to an
372 -- arbitrary thread (GHC only: c.f. 'throwTo').
373 throwDynTo :: Typeable exception => ThreadId -> exception -> IO ()
374 throwDynTo t exception = throwTo t (DynException (toDyn exception))
375 #endif /* __GLASGOW_HASKELL__ */
377 -- | Catch dynamic exceptions of the required type. All other
378 -- exceptions are re-thrown, including dynamic exceptions of the wrong
381 -- When using dynamic exceptions it is advisable to define a new
382 -- datatype to use for your exception type, to avoid possible clashes
383 -- with dynamic exceptions used in other libraries.
385 catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a
387 catchDyn m k = m -- can't catch dyn exceptions in nhc98
389 catchDyn m k = catchException m handle
390 where handle ex = case ex of
391 (DynException dyn) ->
392 case fromDynamic dyn of
393 Just exception -> k exception
398 -----------------------------------------------------------------------------
399 -- Exception Predicates
402 -- These pre-defined predicates may be used as the first argument to
403 -- 'catchJust', 'tryJust', or 'handleJust' to select certain common
404 -- classes of exceptions.
406 ioErrors :: Exception -> Maybe IOError
407 arithExceptions :: Exception -> Maybe ArithException
408 errorCalls :: Exception -> Maybe String
409 assertions :: Exception -> Maybe String
410 dynExceptions :: Exception -> Maybe Dynamic
411 asyncExceptions :: Exception -> Maybe AsyncException
412 userErrors :: Exception -> Maybe String
414 ioErrors (IOException e) = Just e
417 arithExceptions (ArithException e) = Just e
418 arithExceptions _ = Nothing
420 errorCalls (ErrorCall e) = Just e
421 errorCalls _ = Nothing
423 assertions (AssertionFailed e) = Just e
424 assertions _ = Nothing
426 dynExceptions (DynException e) = Just e
427 dynExceptions _ = Nothing
429 asyncExceptions (AsyncException e) = Just e
430 asyncExceptions _ = Nothing
432 userErrors (IOException e) | isUserError e = Just (ioeGetErrorString e)
433 userErrors _ = Nothing
435 -----------------------------------------------------------------------------
436 -- Some Useful Functions
438 -- | When you want to acquire a resource, do some work with it, and
439 -- then release the resource, it is a good idea to use 'bracket',
440 -- because 'bracket' will install the necessary exception handler to
441 -- release the resource in the event that an exception is raised
442 -- during the computation. If an exception is raised, then 'bracket' will
443 -- re-raise the exception (after performing the release).
445 -- A common example is opening a file:
448 -- > (openFile "filename" ReadMode)
450 -- > (\handle -> do { ... })
452 -- The arguments to 'bracket' are in this order so that we can partially apply
455 -- > withFile name mode = bracket (openFile name mode) hClose
459 :: IO a -- ^ computation to run first (\"acquire resource\")
460 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
461 -> (a -> IO c) -- ^ computation to run in-between
462 -> IO c -- returns the value from the in-between computation
463 bracket before after thing =
468 (\e -> do { after a; throw e })
474 -- | A specialised variant of 'bracket' with just a computation to run
477 finally :: IO a -- ^ computation to run first
478 -> IO b -- ^ computation to run afterward (even if an exception
480 -> IO a -- returns the value from the first computation
485 (\e -> do { sequel; throw e })
490 -- | A variant of 'bracket' where the return value from the first computation
492 bracket_ :: IO a -> IO b -> IO c -> IO c
493 bracket_ before after thing = bracket before (const after) (const thing)
495 -- | Like bracket, but only performs the final action if there was an
496 -- exception raised by the in-between computation.
498 :: IO a -- ^ computation to run first (\"acquire resource\")
499 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
500 -> (a -> IO c) -- ^ computation to run in-between
501 -> IO c -- returns the value from the in-between computation
502 bracketOnError before after thing =
507 (\e -> do { after a; throw e })
510 -- -----------------------------------------------------------------------------
511 -- Asynchronous exceptions
515 #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
516 external influences, and can be raised at any point during execution.
517 'StackOverflow' and 'HeapOverflow' are two examples of
518 system-generated asynchronous exceptions.
520 The primary source of asynchronous exceptions, however, is
523 > throwTo :: ThreadId -> Exception -> IO ()
525 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
526 running thread to raise an arbitrary exception in another thread. The
527 exception is therefore asynchronous with respect to the target thread,
528 which could be doing anything at the time it receives the exception.
529 Great care should be taken with asynchronous exceptions; it is all too
530 easy to introduce race conditions by the over zealous use of
535 There\'s an implied 'block' around every exception handler in a call
536 to one of the 'catch' family of functions. This is because that is
537 what you want most of the time - it eliminates a common race condition
538 in starting an exception handler, because there may be no exception
539 handler on the stack to handle another exception if one arrives
540 immediately. If asynchronous exceptions are blocked on entering the
541 handler, though, we have time to install a new exception handler
542 before being interrupted. If this weren\'t the default, one would have
543 to write something like
546 > catch (unblock (...))
550 If you need to unblock asynchronous exceptions again in the exception
551 handler, just use 'unblock' as normal.
553 Note that 'try' and friends /do not/ have a similar default, because
554 there is no exception handler in this case. If you want to use 'try'
555 in an asynchronous-exception-safe way, you will need to use
561 Some operations are /interruptible/, which means that they can receive
562 asynchronous exceptions even in the scope of a 'block'. Any function
563 which may itself block is defined as interruptible; this includes
564 'Control.Concurrent.MVar.takeMVar'
565 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
566 and most operations which perform
567 some I\/O with the outside world. The reason for having
568 interruptible operations is so that we can write things like
572 > catch (unblock (...))
576 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
578 combination could lead to deadlock, because the thread itself would be
579 blocked in a state where it can\'t receive any asynchronous exceptions.
580 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
581 safe in the knowledge that the thread can receive exceptions right up
582 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
583 Similar arguments apply for other interruptible operations like
584 'System.IO.openFile'.
587 #if !(__GLASGOW_HASKELL__ || __NHC__)
588 assert :: Bool -> a -> a
590 assert False _ = throw (AssertionFailed "")
594 #ifdef __GLASGOW_HASKELL__
595 {-# NOINLINE uncaughtExceptionHandler #-}
596 uncaughtExceptionHandler :: IORef (Exception -> IO ())
597 uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler)
599 defaultHandler :: Exception -> IO ()
600 defaultHandler ex = do
601 (hFlush stdout) `catchAny` (\ _ -> return ())
603 Deadlock -> "no threads to run: infinite loop or deadlock?"
605 other -> showsPrec 0 other ""
606 withCString "%s" $ \cfmt ->
607 withCString msg $ \cmsg ->
610 -- don't use errorBelch() directly, because we cannot call varargs functions
612 foreign import ccall unsafe "HsBase.h errorBelch2"
613 errorBelch :: CString -> CString -> IO ()
615 setUncaughtExceptionHandler :: (Exception -> IO ()) -> IO ()
616 setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler
618 getUncaughtExceptionHandler :: IO (Exception -> IO ())
619 getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler