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
11 -- This module provides support for raising and catching both built-in
12 -- and user-defined exceptions.
14 -----------------------------------------------------------------------------
16 module Control.Exception (
18 -- * The Exception type
19 Exception(..), -- instance Eq, Ord, Show, Typeable
20 #ifdef __GLASGOW_HASKELL__
21 IOException, -- instance Eq, Ord, Show, Typeable
22 ArithException(..), -- instance Eq, Ord, Show, Typeable
23 ArrayException(..), -- instance Eq, Ord, Show, Typeable
24 AsyncException(..), -- instance Eq, Ord, Show, Typeable
27 -- * Throwing exceptions
28 throwIO, -- :: Exception -> IO a
30 throw, -- :: Exception -> a
32 ioError, -- :: IOError -> IO a
34 throwTo, -- :: ThreadId -> Exception -> a
37 -- * Catching Exceptions
39 -- |There are several functions for catching and examining
40 -- exceptions; all of them may only be used from within the
43 -- ** The @catch@ functions
44 catch, -- :: IO a -> (Exception -> IO a) -> IO a
45 catchJust, -- :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a
47 -- ** The @handle@ functions
48 handle, -- :: (Exception -> IO a) -> IO a -> IO a
49 handleJust,-- :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
51 -- ** The @try@ functions
52 try, -- :: IO a -> IO (Either Exception a)
53 tryJust, -- :: (Exception -> Maybe b) -> a -> IO (Either b a)
55 -- ** The @evaluate@ function
56 evaluate, -- :: a -> IO a
58 -- ** The @mapException@ function
59 mapException, -- :: (Exception -> Exception) -> a -> a
61 -- ** Exception predicates
65 ioErrors, -- :: Exception -> Maybe IOError
67 arithExceptions, -- :: Exception -> Maybe ArithException
68 errorCalls, -- :: Exception -> Maybe String
69 dynExceptions, -- :: Exception -> Maybe Dynamic
70 assertions, -- :: Exception -> Maybe String
71 asyncExceptions, -- :: Exception -> Maybe AsyncException
73 userErrors, -- :: Exception -> Maybe String
75 #ifdef __GLASGOW_HASKELL__
76 -- * Dynamic exceptions
79 throwDyn, -- :: Typeable ex => ex -> b
80 throwDynTo, -- :: Typeable ex => ThreadId -> ex -> b
81 catchDyn, -- :: Typeable ex => IO a -> (ex -> IO a) -> IO a
84 -- * Asynchronous Exceptions
88 -- ** Asynchronous exception control
90 -- |The following two functions allow a thread to control delivery of
91 -- asynchronous exceptions during a critical region.
93 block, -- :: IO a -> IO a
94 unblock, -- :: IO a -> IO a
96 -- *** Applying @block@ to an exception handler
100 -- *** Interruptible operations
106 assert, -- :: Bool -> a -> a
110 bracket, -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO ()
111 bracket_, -- :: IO a -> IO b -> IO c -> IO ()
113 finally, -- :: IO a -> IO b -> IO b
117 #ifdef __GLASGOW_HASKELL__
118 import GHC.Base ( assert )
119 import GHC.Exception as ExceptionBase hiding (catch)
120 import GHC.Conc ( throwTo, ThreadId )
121 import GHC.IOBase ( IO(..) )
125 import Hugs.Exception as ExceptionBase
128 import Prelude hiding ( catch )
129 import System.IO.Error hiding ( catch, try )
130 import System.IO.Unsafe (unsafePerformIO)
134 INSTANCE_TYPEABLE0(Exception,exceptionTc,"Exception")
135 #ifdef __GLASGOW_HASKELL__
136 INSTANCE_TYPEABLE0(IOException,ioExceptionTc,"IOException")
137 INSTANCE_TYPEABLE0(ArithException,arithExceptionTc,"ArithException")
138 INSTANCE_TYPEABLE0(ArrayException,arrayExceptionTc,"ArrayException")
139 INSTANCE_TYPEABLE0(AsyncException,asyncExceptionTc,"AsyncException")
143 -- This is as close as Hugs gets to providing throw
144 throw :: Exception -> IO a
148 -----------------------------------------------------------------------------
149 -- Catching exceptions
151 -- |This is the simplest of the exception-catching functions. It
152 -- takes a single argument, runs it, and if an exception is raised
153 -- the \"handler\" is executed, with the value of the exception passed as an
154 -- argument. Otherwise, the result is returned as normal. For example:
156 -- > catch (openFile f ReadMode)
157 -- > (\e -> hPutStr stderr (\"Couldn\'t open \"++f++\": \" ++ show e))
159 -- For catching exceptions in pure (non-'IO') expressions, see the
160 -- function 'evaluate'.
162 -- Note that due to Haskell\'s unspecified evaluation order, an
163 -- expression may return one of several possible exceptions: consider
164 -- the expression @error \"urk\" + 1 \`div\` 0@. Does
165 -- 'catch' execute the handler passing
166 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
168 -- The answer is \"either\": 'catch' makes a
169 -- non-deterministic choice about which exception to catch. If you
170 -- call it again, you might get a different exception back. This is
171 -- ok, because 'catch' is an 'IO' computation.
173 -- Note that 'catch' catches all types of exceptions, and is generally
174 -- used for \"cleaning up\" before passing on the exception using
175 -- 'throwIO'. It is not good practice to discard the exception and
176 -- continue, without first checking the type of the exception (it
177 -- might be a 'ThreadKilled', for example). In this case it is usually better
178 -- to use 'catchJust' and select the kinds of exceptions to catch.
180 -- Also note that The "Prelude" also exports a
181 -- function called 'catch' which has the same type as
182 -- 'Exception.catch', the difference being that the
183 -- "Prelude" version only catches the IO and user
184 -- families of exceptions (as required by Haskell 98). We recommend
185 -- either hiding the "Prelude" version of
186 -- 'catch' when importing
187 -- "Control.Exception", or importing
188 -- "Control.Exception" qualified, to avoid name-clashes.
190 catch :: IO a -- ^ The computation to run
191 -> (Exception -> IO a) -- ^ Handler to invoke if an exception is raised
193 catch = ExceptionBase.catchException
195 -- | The function 'catchJust' is like 'catch', but it takes an extra
196 -- argument which is an /exception predicate/, a function which
197 -- selects which type of exceptions we\'re interested in. There are
198 -- some predefined exception predicates for useful subsets of
199 -- exceptions: 'ioErrors', 'arithExceptions', and so on. For example,
200 -- to catch just calls to the 'error' function, we could use
202 -- > result \<- catchJust errorCalls thing_to_try handler
204 -- Any other exceptions which are not matched by the predicate
205 -- are re-raised, and may be caught by an enclosing
206 -- 'catch' or 'catchJust'.
208 :: (Exception -> Maybe b) -- ^ Predicate to select exceptions
209 -> IO a -- ^ Computation to run
210 -> (b -> IO a) -- ^ Handler
212 catchJust p a handler = catch a handler'
213 where handler' e = case p e of
217 -- | A version of 'catch' with the arguments swapped around; useful in
218 -- situations where the code for the handler is shorter. For example:
220 -- > do handle (\e -> exitWith (ExitFailure 1)) $
222 handle :: (Exception -> IO a) -> IO a -> IO a
225 -- | A version of 'catchJust' with the arguments swapped around (see
227 handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
228 handleJust p = flip (catchJust p)
230 -----------------------------------------------------------------------------
233 -- | Forces its argument to be evaluated, and returns the result in
234 -- the 'IO' monad. It can be used to order evaluation with respect to
235 -- other 'IO' operations; its semantics are given by
237 -- > evaluate undefined `seq` return () ==> return ()
238 -- > catch (evaluate undefined) (\e -> return ()) ==> return ()
240 -- NOTE: @(evaluate a)@ is /not/ the same as @(a \`seq\` return a)@.
241 #ifdef __GLASGOW_HASKELL__
242 evaluate :: a -> IO a
243 evaluate a = IO $ \s -> case a `seq` () of () -> (# s, a #)
245 -- a `seq` (# s, a #)
246 -- because we can't have an unboxed tuple as a function argument
249 -----------------------------------------------------------------------------
252 -- | This function maps one exception into another as proposed in the
253 -- paper "A semantics for imprecise exceptions".
255 -- Notice that the usage of 'unsafePerformIO' is safe here.
257 mapException :: (Exception -> Exception) -> a -> a
258 mapException f v = unsafePerformIO (catch (evaluate v)
261 -----------------------------------------------------------------------------
262 -- 'try' and variations.
264 -- | Similar to 'catch', but returns an 'Either' result which is
265 -- @(Right a)@ if no exception was raised, or @(Left e)@ if an
266 -- exception was raised and its value is @e@.
268 -- > try a = catch (Right \`liftM\` a) (return . Left)
270 -- Note: as with 'catch', it is only polite to use this variant if you intend
271 -- to re-throw the exception after performing whatever cleanup is needed.
272 -- Otherwise, 'tryJust' is generally considered to be better.
274 try :: IO a -> IO (Either Exception a)
275 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
277 -- | A variant of 'try' that takes an exception predicate to select
278 -- which exceptions are caught (c.f. 'catchJust'). If the exception
279 -- does not match the predicate, it is re-thrown.
280 tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a)
284 Right v -> return (Right v)
285 Left e -> case p e of
287 Just b -> return (Left b)
289 #ifdef __GLASGOW_HASKELL__
290 -----------------------------------------------------------------------------
291 -- Dynamic exceptions
294 -- #DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an
295 -- interface for throwing and catching exceptions of type 'Dynamic'
296 -- (see "Data.Dynamic") which allows exception values of any type in
297 -- the 'Typeable' class to be thrown and caught.
299 -- | Raise any value as an exception, provided it is in the
301 throwDyn :: Typeable exception => exception -> b
302 throwDyn exception = throw (DynException (toDyn exception))
304 -- | A variant of 'throwDyn' that throws the dynamic exception to an
305 -- arbitrary thread (c.f. 'throwTo').
306 throwDynTo :: Typeable exception => ThreadId -> exception -> IO ()
307 throwDynTo t exception = throwTo t (DynException (toDyn exception))
309 -- | Catch dynamic exceptions of the required type. All other
310 -- exceptions are re-thrown, including dynamic exceptions of the wrong
313 -- When using dynamic exceptions it is advisable to define a new
314 -- datatype to use for your exception type, to avoid possible clashes
315 -- with dynamic exceptions used in other libraries.
317 catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a
318 catchDyn m k = catchException m handle
319 where handle ex = case ex of
320 (DynException dyn) ->
321 case fromDynamic dyn of
322 Just exception -> k exception
325 #endif /* __GLASGOW_HASKELL__ */
327 -----------------------------------------------------------------------------
328 -- Exception Predicates
331 -- These pre-defined predicates may be used as the first argument to
332 -- 'catchJust', 'tryJust', or 'handleJust' to select certain common
333 -- classes of exceptions.
335 #ifdef __GLASGOW_HASKELL__
336 ioErrors :: Exception -> Maybe IOError
337 arithExceptions :: Exception -> Maybe ArithException
338 errorCalls :: Exception -> Maybe String
339 dynExceptions :: Exception -> Maybe Dynamic
340 assertions :: Exception -> Maybe String
341 asyncExceptions :: Exception -> Maybe AsyncException
342 userErrors :: Exception -> Maybe String
343 #endif /* __GLASGOW_HASKELL__ */
345 #ifdef __GLASGOW_HASKELL__
346 ioErrors (IOException e) = Just e
349 arithExceptions (ArithException e) = Just e
350 arithExceptions _ = Nothing
352 errorCalls (ErrorCall e) = Just e
353 errorCalls _ = Nothing
355 assertions (AssertionFailed e) = Just e
356 assertions _ = Nothing
358 dynExceptions (DynException e) = Just e
359 dynExceptions _ = Nothing
361 asyncExceptions (AsyncException e) = Just e
362 asyncExceptions _ = Nothing
364 userErrors (IOException e) | isUserError e = Just (ioeGetErrorString e)
365 userErrors _ = Nothing
366 #endif /* __GLASGOW_HASKELL__ */
368 -----------------------------------------------------------------------------
369 -- Some Useful Functions
371 -- | When you want to acquire a resource, do some work with it, and
372 -- then release the resource, it is a good idea to use 'bracket',
373 -- because 'bracket' will install the necessary exception handler to
374 -- release the resource in the event that an exception is raised
375 -- during the computation. If an exception is raised, then 'bracket' will
376 -- re-raise the exception (after performing the release).
378 -- A common example is opening a file:
381 -- > (openFile "filename" ReadMode)
383 -- > (\handle -> do { ... })
385 -- The arguments to 'bracket' are in this order so that we can partially apply
388 -- > withFile name = bracket (openFile name) hClose
391 :: IO a -- ^ computation to run first (\"acquire resource\")
392 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
393 -> (a -> IO c) -- ^ computation to run in-between
394 -> IO c -- returns the value from the in-between computation
395 bracket before after thing =
400 (\e -> do { after a; throw e })
406 -- | A specialised variant of 'bracket' with just a computation to run
409 finally :: IO a -- ^ computation to run first
410 -> IO b -- ^ computation to run afterward (even if an exception
412 -> IO a -- returns the value from the first computation
417 (\e -> do { sequel; throw e })
422 -- | A variant of 'bracket' where the return value from the first computation
424 bracket_ :: IO a -> IO b -> IO c -> IO c
425 bracket_ before after thing = bracket before (const after) (const thing)
427 -- -----------------------------------------------------------------------------
428 -- Asynchronous exceptions
432 #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
433 external influences, and can be raised at any point during execution.
434 'StackOverflow' and 'HeapOverflow' are two examples of
435 system-generated asynchronous exceptions.
437 The primary source of asynchronous exceptions, however, is
440 > throwTo :: ThreadId -> Exception -> IO ()
442 'throwTo' (also 'throwDynTo' and 'Concurrent.killThread') allows one
443 running thread to raise an arbitrary exception in another thread. The
444 exception is therefore asynchronous with respect to the target thread,
445 which could be doing anything at the time it receives the exception.
446 Great care should be taken with asynchronous exceptions; it is all too
447 easy to introduce race conditions by the over zealous use of
452 There\'s an implied 'block' around every exception handler in a call
453 to one of the 'catch' family of functions. This is because that is
454 what you want most of the time - it eliminates a common race condition
455 in starting an exception handler, because there may be no exception
456 handler on the stack to handle another exception if one arrives
457 immediately. If asynchronous exceptions are blocked on entering the
458 handler, though, we have time to install a new exception handler
459 before being interrupted. If this weren\'t the default, one would have
460 to write something like
463 > catch (unblock (...))
467 If you need to unblock asynchronous exceptions again in the exception
468 handler, just use 'unblock' as normal.
470 Note that 'try' and friends /do not/ have a similar default, because
471 there is no exception handler in this case. If you want to use 'try'
472 in an asynchronous-exception-safe way, you will need to use
478 Some operations are /interruptible/, which means that they can receive
479 asynchronous exceptions even in the scope of a 'block'. Any function
480 which may itself block is defined as interruptible; this includes
481 'takeMVar' (but not 'tryTakeMVar'), and most operations which perform
482 some I\/O with the outside world.. The reason for having
483 interruptible operations is so that we can write things like
487 > catch (unblock (...))
491 if the 'takeMVar' was not interruptible, then this particular
492 combination could lead to deadlock, because the thread itself would be
493 blocked in a state where it can\'t receive any asynchronous exceptions.
494 With 'takeMVar' interruptible, however, we can be
495 safe in the knowledge that the thread can receive exceptions right up
496 until the point when the 'takeMVar' succeeds.
497 Similar arguments apply for other interruptible operations like
501 -- -----------------------------------------------------------------------------
505 -- | If the first argument evaluates to 'True', then the result is the
506 -- second argument. Otherwise an 'Assertion' exception is raised,
507 -- containing a 'String' with the source file and line number of the
510 -- Assertions can normally be turned on or off with a compiler flag
511 -- (for GHC, assertions are normally on unless the @-fignore-asserts@
512 -- option is give). When assertions are turned off, the first
513 -- argument to 'assert' is ignored, and the second argument is
514 -- returned as the result.
515 assert :: Bool -> a -> a
518 #ifndef __GLASGOW_HASKELL__
519 assert :: Bool -> a -> a
521 assert False _ = error "Assertion failure"