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 evaluate :: a -> IO a
242 #if defined(__GLASGOW_HASKELL__)
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
247 #elif defined(__HUGS__)
248 evaluate a = a `seq` return a -- dummy implementation: to be fixed
251 -----------------------------------------------------------------------------
254 -- | This function maps one exception into another as proposed in the
255 -- paper "A semantics for imprecise exceptions".
257 -- Notice that the usage of 'unsafePerformIO' is safe here.
259 mapException :: (Exception -> Exception) -> a -> a
260 mapException f v = unsafePerformIO (catch (evaluate v)
263 -----------------------------------------------------------------------------
264 -- 'try' and variations.
266 -- | Similar to 'catch', but returns an 'Either' result which is
267 -- @(Right a)@ if no exception was raised, or @(Left e)@ if an
268 -- exception was raised and its value is @e@.
270 -- > try a = catch (Right \`liftM\` a) (return . Left)
272 -- Note: as with 'catch', it is only polite to use this variant if you intend
273 -- to re-throw the exception after performing whatever cleanup is needed.
274 -- Otherwise, 'tryJust' is generally considered to be better.
276 try :: IO a -> IO (Either Exception a)
277 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
279 -- | A variant of 'try' that takes an exception predicate to select
280 -- which exceptions are caught (c.f. 'catchJust'). If the exception
281 -- does not match the predicate, it is re-thrown.
282 tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a)
286 Right v -> return (Right v)
287 Left e -> case p e of
289 Just b -> return (Left b)
291 #ifdef __GLASGOW_HASKELL__
292 -----------------------------------------------------------------------------
293 -- Dynamic exceptions
296 -- #DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an
297 -- interface for throwing and catching exceptions of type 'Dynamic'
298 -- (see "Data.Dynamic") which allows exception values of any type in
299 -- the 'Typeable' class to be thrown and caught.
301 -- | Raise any value as an exception, provided it is in the
303 throwDyn :: Typeable exception => exception -> b
304 throwDyn exception = throw (DynException (toDyn exception))
306 -- | A variant of 'throwDyn' that throws the dynamic exception to an
307 -- arbitrary thread (c.f. 'throwTo').
308 throwDynTo :: Typeable exception => ThreadId -> exception -> IO ()
309 throwDynTo t exception = throwTo t (DynException (toDyn exception))
311 -- | Catch dynamic exceptions of the required type. All other
312 -- exceptions are re-thrown, including dynamic exceptions of the wrong
315 -- When using dynamic exceptions it is advisable to define a new
316 -- datatype to use for your exception type, to avoid possible clashes
317 -- with dynamic exceptions used in other libraries.
319 catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a
320 catchDyn m k = catchException m handle
321 where handle ex = case ex of
322 (DynException dyn) ->
323 case fromDynamic dyn of
324 Just exception -> k exception
327 #endif /* __GLASGOW_HASKELL__ */
329 -----------------------------------------------------------------------------
330 -- Exception Predicates
333 -- These pre-defined predicates may be used as the first argument to
334 -- 'catchJust', 'tryJust', or 'handleJust' to select certain common
335 -- classes of exceptions.
337 #ifdef __GLASGOW_HASKELL__
338 ioErrors :: Exception -> Maybe IOError
339 arithExceptions :: Exception -> Maybe ArithException
340 errorCalls :: Exception -> Maybe String
341 dynExceptions :: Exception -> Maybe Dynamic
342 assertions :: Exception -> Maybe String
343 asyncExceptions :: Exception -> Maybe AsyncException
344 userErrors :: Exception -> Maybe String
345 #endif /* __GLASGOW_HASKELL__ */
347 #ifdef __GLASGOW_HASKELL__
348 ioErrors (IOException e) = Just e
351 arithExceptions (ArithException e) = Just e
352 arithExceptions _ = Nothing
354 errorCalls (ErrorCall e) = Just e
355 errorCalls _ = Nothing
357 assertions (AssertionFailed e) = Just e
358 assertions _ = Nothing
360 dynExceptions (DynException e) = Just e
361 dynExceptions _ = Nothing
363 asyncExceptions (AsyncException e) = Just e
364 asyncExceptions _ = Nothing
366 userErrors (IOException e) | isUserError e = Just (ioeGetErrorString e)
367 userErrors _ = Nothing
368 #endif /* __GLASGOW_HASKELL__ */
370 -----------------------------------------------------------------------------
371 -- Some Useful Functions
373 -- | When you want to acquire a resource, do some work with it, and
374 -- then release the resource, it is a good idea to use 'bracket',
375 -- because 'bracket' will install the necessary exception handler to
376 -- release the resource in the event that an exception is raised
377 -- during the computation. If an exception is raised, then 'bracket' will
378 -- re-raise the exception (after performing the release).
380 -- A common example is opening a file:
383 -- > (openFile "filename" ReadMode)
385 -- > (\handle -> do { ... })
387 -- The arguments to 'bracket' are in this order so that we can partially apply
390 -- > withFile name = bracket (openFile name) hClose
393 :: IO a -- ^ computation to run first (\"acquire resource\")
394 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
395 -> (a -> IO c) -- ^ computation to run in-between
396 -> IO c -- returns the value from the in-between computation
397 bracket before after thing =
402 (\e -> do { after a; throw e })
408 -- | A specialised variant of 'bracket' with just a computation to run
411 finally :: IO a -- ^ computation to run first
412 -> IO b -- ^ computation to run afterward (even if an exception
414 -> IO a -- returns the value from the first computation
419 (\e -> do { sequel; throw e })
424 -- | A variant of 'bracket' where the return value from the first computation
426 bracket_ :: IO a -> IO b -> IO c -> IO c
427 bracket_ before after thing = bracket before (const after) (const thing)
429 -- -----------------------------------------------------------------------------
430 -- Asynchronous exceptions
434 #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
435 external influences, and can be raised at any point during execution.
436 'StackOverflow' and 'HeapOverflow' are two examples of
437 system-generated asynchronous exceptions.
439 The primary source of asynchronous exceptions, however, is
442 > throwTo :: ThreadId -> Exception -> IO ()
444 'throwTo' (also 'throwDynTo' and 'Concurrent.killThread') allows one
445 running thread to raise an arbitrary exception in another thread. The
446 exception is therefore asynchronous with respect to the target thread,
447 which could be doing anything at the time it receives the exception.
448 Great care should be taken with asynchronous exceptions; it is all too
449 easy to introduce race conditions by the over zealous use of
454 There\'s an implied 'block' around every exception handler in a call
455 to one of the 'catch' family of functions. This is because that is
456 what you want most of the time - it eliminates a common race condition
457 in starting an exception handler, because there may be no exception
458 handler on the stack to handle another exception if one arrives
459 immediately. If asynchronous exceptions are blocked on entering the
460 handler, though, we have time to install a new exception handler
461 before being interrupted. If this weren\'t the default, one would have
462 to write something like
465 > catch (unblock (...))
469 If you need to unblock asynchronous exceptions again in the exception
470 handler, just use 'unblock' as normal.
472 Note that 'try' and friends /do not/ have a similar default, because
473 there is no exception handler in this case. If you want to use 'try'
474 in an asynchronous-exception-safe way, you will need to use
480 Some operations are /interruptible/, which means that they can receive
481 asynchronous exceptions even in the scope of a 'block'. Any function
482 which may itself block is defined as interruptible; this includes
483 'takeMVar' (but not 'tryTakeMVar'), and most operations which perform
484 some I\/O with the outside world.. The reason for having
485 interruptible operations is so that we can write things like
489 > catch (unblock (...))
493 if the 'takeMVar' was not interruptible, then this particular
494 combination could lead to deadlock, because the thread itself would be
495 blocked in a state where it can\'t receive any asynchronous exceptions.
496 With 'takeMVar' interruptible, however, we can be
497 safe in the knowledge that the thread can receive exceptions right up
498 until the point when the 'takeMVar' succeeds.
499 Similar arguments apply for other interruptible operations like
503 -- -----------------------------------------------------------------------------
507 -- | If the first argument evaluates to 'True', then the result is the
508 -- second argument. Otherwise an 'Assertion' exception is raised,
509 -- containing a 'String' with the source file and line number of the
512 -- Assertions can normally be turned on or off with a compiler flag
513 -- (for GHC, assertions are normally on unless the @-fignore-asserts@
514 -- option is give). When assertions are turned off, the first
515 -- argument to 'assert' is ignored, and the second argument is
516 -- returned as the result.
517 assert :: Bool -> a -> a
520 #ifndef __GLASGOW_HASKELL__
521 assert :: Bool -> a -> a
523 assert False _ = error "Assertion failure"