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 IOException, -- instance Eq, Ord, Show, Typeable
21 ArithException(..), -- instance Eq, Ord, Show, Typeable
22 ArrayException(..), -- instance Eq, Ord, Show, Typeable
23 AsyncException(..), -- instance Eq, Ord, Show, Typeable
25 -- * Throwing exceptions
26 throw, -- :: Exception -> a
27 ioError, -- :: Exception -> IO a
28 throwTo, -- :: ThreadId -> Exception -> a
30 -- * Catching Exceptions
32 -- |There are several functions for catching and examining
33 -- exceptions; all of them may only be used from within the
36 -- ** The @catch@ functions
37 catch, -- :: IO a -> (Exception -> IO a) -> IO a
38 catchJust, -- :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a
40 -- ** The @handle@ functions
41 handle, -- :: (Exception -> IO a) -> IO a -> IO a
42 handleJust,-- :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
44 -- ** The @try@ functions
45 try, -- :: IO a -> IO (Either Exception a)
46 tryJust, -- :: (Exception -> Maybe b) -> a -> IO (Either b a)
48 -- ** The @evaluate@ function
49 evaluate, -- :: a -> IO a
51 -- ** Exception predicates
55 ioErrors, -- :: Exception -> Maybe IOError
56 arithExceptions, -- :: Exception -> Maybe ArithException
57 errorCalls, -- :: Exception -> Maybe String
58 dynExceptions, -- :: Exception -> Maybe Dynamic
59 assertions, -- :: Exception -> Maybe String
60 asyncExceptions, -- :: Exception -> Maybe AsyncException
61 userErrors, -- :: Exception -> Maybe String
63 -- * Dynamic exceptions
66 throwDyn, -- :: Typeable ex => ex -> b
67 throwDynTo, -- :: Typeable ex => ThreadId -> ex -> b
68 catchDyn, -- :: Typeable ex => IO a -> (ex -> IO a) -> IO a
70 -- * Asynchronous Exceptions
74 -- ** Asynchronous exception control
76 -- |The following two functions allow a thread to control delivery of
77 -- asynchronous exceptions during a critical region.
79 block, -- :: IO a -> IO a
80 unblock, -- :: IO a -> IO a
82 -- *** Applying @block@ to an exception handler
86 -- *** Interruptible operations
92 assert, -- :: Bool -> a -> a
96 bracket, -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO ()
97 bracket_, -- :: IO a -> IO b -> IO c -> IO ()
99 finally, -- :: IO a -> IO b -> IO b
103 #ifdef __GLASGOW_HASKELL__
104 import Prelude hiding (catch)
105 import System.IO.Error
106 import GHC.Base ( assert )
107 import GHC.Exception hiding (try, catch, bracket, bracket_)
108 import GHC.Conc ( throwTo, ThreadId )
109 import GHC.IOBase ( IO(..) )
113 import Prelude hiding ( catch )
114 import PrelPrim ( catchException
126 INSTANCE_TYPEABLE0(Exception,exceptionTc,"Exception")
127 INSTANCE_TYPEABLE0(IOException,ioExceptionTc,"IOException")
128 INSTANCE_TYPEABLE0(ArithException,arithExceptionTc,"ArithException")
129 INSTANCE_TYPEABLE0(ArrayException,arrayExceptionTc,"ArrayException")
130 INSTANCE_TYPEABLE0(AsyncException,asyncExceptionTc,"AsyncException")
132 -----------------------------------------------------------------------------
133 -- Catching exceptions
135 -- |This is the simplest of the exception-catching functions. It
136 -- takes a single argument, runs it, and if an exception is raised
137 -- the \"handler\" is executed, with the value of the exception passed as an
138 -- argument. Otherwise, the result is returned as normal. For example:
140 -- > catch (openFile f ReadMode)
141 -- > (\e -> hPutStr stderr (\"Couldn\'t open \"++f++\": \" ++ show e))
143 -- For catching exceptions in pure (non-'IO') expressions, see the
144 -- function 'evaluate'.
146 -- Note that due to Haskell\'s unspecified evaluation order, an
147 -- expression may return one of several possible exceptions: consider
148 -- the expression @error \"urk\" + 1 \`div\` 0@. Does
149 -- 'catch' execute the handler passing
150 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
152 -- The answer is \"either\": 'catch' makes a
153 -- non-deterministic choice about which exception to catch. If you
154 -- call it again, you might get a different exception back. This is
155 -- ok, because 'catch' is an 'IO' computation.
157 -- Note that 'catch' catches all types of exceptions, and is generally
158 -- used for \"cleaning up\" before passing on the exception using
159 -- 'ioError'. It is not good practice to discard the exception and
160 -- continue, without first checking the type of the exception (it
161 -- might be a 'ThreadKilled', for example). In this case it is usually better
162 -- to use 'catchJust' and select the kinds of exceptions to catch.
164 -- Also note that The "Prelude" also exports a
165 -- function called 'catch' which has the same type as
166 -- 'Exception.catch', the difference being that the
167 -- "Prelude" version only catches the IO and user
168 -- families of exceptions (as required by Haskell 98). We recommend
169 -- either hiding the "Prelude" version of
170 -- 'catch' when importing
171 -- "Control.Exception", or importing
172 -- "Control.Exception" qualified, to avoid name-clashes.
174 catch :: IO a -- ^ The computation to run
175 -> (Exception -> IO a) -- ^ Handler to invoke if an exception is raised
177 catch = GHC.Exception.catchException
179 -- | The function 'catchJust' is like 'catch', but it takes an extra
180 -- argument which is an /exception predicate/, a function which
181 -- selects which type of exceptions we\'re interested in. There are
182 -- some predefined exception predicates for useful subsets of
183 -- exceptions: 'ioErrors', 'arithExceptions', and so on. For example,
184 -- to catch just calls to the 'error' function, we could use
186 -- > result \<- catchJust errorCalls thing_to_try handler
188 -- Any other exceptions which are not matched by the predicate
189 -- are re-raised, and may be caught by an enclosing
190 -- 'catch' or 'catchJust'.
192 :: (Exception -> Maybe b) -- ^ Predicate to select exceptions
193 -> IO a -- ^ Computation to run
194 -> (b -> IO a) -- ^ Handler
196 catchJust p a handler = catch a handler'
197 where handler' e = case p e of
201 -- | A version of 'catch' with the arguments swapped around; useful in
202 -- situations where the code for the handler is shorter. For example:
204 -- > do handle (\e -> exitWith (ExitFailure 1)) $
206 handle :: (Exception -> IO a) -> IO a -> IO a
209 -- | A version of 'catchJust' with the arguments swapped around (see
211 handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
212 handleJust p = flip (catchJust p)
214 -----------------------------------------------------------------------------
217 -- | Forces its argument to be evaluated, and returns the result in
218 -- the 'IO' monad. It can be used to order evaluation with respect to
219 -- other 'IO' operations; its semantics are given by
221 -- > evaluate undefined `seq` return () ==> return ()
222 -- > catch (evaluate undefined) (\e -> return ()) ==> return ()
224 -- NOTE: @(evaluate a)@ is /not/ the same as @(a \`seq\` return a)@.
225 evaluate :: a -> IO a
226 evaluate a = IO $ \s -> case a `seq` () of () -> (# s, a #)
228 -- a `seq` (# s, a #)
229 -- because we can't have an unboxed tuple as a function argument
231 -----------------------------------------------------------------------------
232 -- 'try' and variations.
234 -- | Similar to 'catch', but returns an 'Either' result which is
235 -- @(Right a)@ if no exception was raised, or @(Left e)@ if an
236 -- exception was raised and its value is @e@.
238 -- > try a = catch (Right \`liftM\` a) (return . Left)
240 -- Note: as with 'catch', it is only polite to use this variant if you intend
241 -- to re-throw the exception after performing whatever cleanup is needed.
242 -- Otherwise, 'tryJust' is generally considered to be better.
244 try :: IO a -> IO (Either Exception a)
245 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
247 -- | A variant of 'try' that takes an exception predicate to select
248 -- which exceptions are caught (c.f. 'catchJust'). If the exception
249 -- does not match the predicate, it is re-thrown.
250 tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a)
254 Right v -> return (Right v)
255 Left e -> case p e of
257 Just b -> return (Left b)
259 -----------------------------------------------------------------------------
260 -- Dynamic exceptions
263 -- #DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an
264 -- interface for throwing and catching exceptions of type 'Dynamic'
265 -- (see "Data.Dynamic") which allows exception values of any type in
266 -- the 'Typeable' class to be thrown and caught.
268 -- | Raise any value as an exception, provided it is in the
270 throwDyn :: Typeable exception => exception -> b
271 throwDyn exception = throw (DynException (toDyn exception))
273 -- | A variant of 'throwDyn' that throws the dynamic exception to an
274 -- arbitrary thread (c.f. 'throwTo').
275 throwDynTo :: Typeable exception => ThreadId -> exception -> IO ()
276 throwDynTo t exception = throwTo t (DynException (toDyn exception))
278 -- | Catch dynamic exceptions of the required type. All other
279 -- exceptions are re-thrown, including dynamic exceptions of the wrong
282 -- When using dynamic exceptions it is advisable to define a new
283 -- datatype to use for your exception type, to avoid possible clashes
284 -- with dynamic exceptions used in other libraries.
286 catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a
287 catchDyn m k = catchException m handle
288 where handle ex = case ex of
289 (DynException dyn) ->
290 case fromDynamic dyn of
291 Just exception -> k exception
295 -----------------------------------------------------------------------------
296 -- Exception Predicates
299 -- These pre-defined predicates may be used as the first argument to
300 -- 'catchJust', 'tryJust', or 'handleJust' to select certain common
301 -- classes of exceptions.
303 ioErrors :: Exception -> Maybe IOError
304 arithExceptions :: Exception -> Maybe ArithException
305 errorCalls :: Exception -> Maybe String
306 dynExceptions :: Exception -> Maybe Dynamic
307 assertions :: Exception -> Maybe String
308 asyncExceptions :: Exception -> Maybe AsyncException
309 userErrors :: Exception -> Maybe String
311 ioErrors e@(IOException _) = Just e
314 arithExceptions (ArithException e) = Just e
315 arithExceptions _ = Nothing
317 errorCalls (ErrorCall e) = Just e
318 errorCalls _ = Nothing
320 assertions (AssertionFailed e) = Just e
321 assertions _ = Nothing
323 dynExceptions (DynException e) = Just e
324 dynExceptions _ = Nothing
326 asyncExceptions (AsyncException e) = Just e
327 asyncExceptions _ = Nothing
329 userErrors e | isUserError e = Just (ioeGetErrorString e)
330 userErrors _ = Nothing
332 -----------------------------------------------------------------------------
333 -- Some Useful Functions
335 -- | When you want to acquire a resource, do some work with it, and
336 -- then release the resource, it is a good idea to use 'bracket',
337 -- because 'bracket' will install the necessary exception handler to
338 -- release the resource in the event that an exception is raised
339 -- during the computation. If an exception is raised, then 'bracket' will
340 -- re-raise the exception (after performing the release).
342 -- A common example is opening a file:
345 -- > (openFile "filename" ReadMode)
347 -- > (\handle -> do { ... })
349 -- The arguments to 'bracket' are in this order so that we can partially apply
352 -- > withFile name = bracket (openFile name) hClose
355 :: IO a -- ^ computation to run first (\"acquire resource\")
356 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
357 -> (a -> IO c) -- ^ computation to run in-between
358 -> IO c -- returns the value from the in-between computation
359 bracket before after thing =
364 (\e -> do { after a; throw e })
370 -- | A specialised variant of 'bracket' with just a computation to run
373 finally :: IO a -- ^ computation to run first
374 -> IO b -- ^ computation to run afterward (even if an exception
376 -> IO a -- returns the value from the first computation
381 (\e -> do { sequel; throw e })
386 -- | A variant of 'bracket' where the return value from the first computation
388 bracket_ :: IO a -> IO b -> IO c -> IO c
389 bracket_ before after thing = bracket before (const after) (const thing)
391 -- -----------------------------------------------------------------------------
392 -- Asynchronous exceptions
396 #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
397 external influences, and can be raised at any point during execution.
398 'StackOverflow' and 'HeapOverflow' are two examples of
399 system-generated asynchronous exceptions.
401 The primary source of asynchronous exceptions, however, is
404 > throwTo :: ThreadId -> Exception -> IO ()
406 'throwTo' (also 'throwDynTo' and 'Concurrent.killThread') allows one
407 running thread to raise an arbitrary exception in another thread. The
408 exception is therefore asynchronous with respect to the target thread,
409 which could be doing anything at the time it receives the exception.
410 Great care should be taken with asynchronous exceptions; it is all too
411 easy to introduce race conditions by the over zealous use of
416 There\'s an implied 'block' around every exception handler in a call
417 to one of the 'catch' family of functions. This is because that is
418 what you want most of the time - it eliminates a common race condition
419 in starting an exception handler, because there may be no exception
420 handler on the stack to handle another exception if one arrives
421 immediately. If asynchronous exceptions are blocked on entering the
422 handler, though, we have time to install a new exception handler
423 before being interrupted. If this weren\'t the default, one would have
424 to write something like
427 > catch (unblock (...))
431 If you need to unblock asynchronous exceptions again in the exception
432 handler, just use 'unblock' as normal.
434 Note that 'try' and friends /do not/ have a similar default, because
435 there is no exception handler in this case. If you want to use 'try'
436 in an asynchronous-exception-safe way, you will need to use
442 Some operations are /interruptible/, which means that they can receive
443 asynchronous exceptions even in the scope of a 'block'. Any function
444 which may itself block is defined as interruptible; this includes
445 'takeMVar' (but not 'tryTakeMVar'), and most operations which perform
446 some I\/O with the outside world.. The reason for having
447 interruptible operations is so that we can write things like
451 > catch (unblock (...))
455 if the 'takeMVar' was not interruptible, then this particular
456 combination could lead to deadlock, because the thread itself would be
457 blocked in a state where it can\'t receive any asynchronous exceptions.
458 With 'takeMVar' interruptible, however, we can be
459 safe in the knowledge that the thread can receive exceptions right up
460 until the point when the 'takeMVar' succeeds.
461 Similar arguments apply for other interruptible operations like
465 -- -----------------------------------------------------------------------------
469 -- | If the first argument evaluates to 'True', then the result is the
470 -- second argument. Otherwise an 'Assertion' exception is raised,
471 -- containing a 'String' with the source file and line number of the
474 -- Assertions can normally be turned on or off with a compiler flag
475 -- (for GHC, assertions are normally on unless the @-fignore-asserts@
476 -- option is give). When assertions are turned off, the first
477 -- argument to 'assert' is ignored, and the second argument is
478 -- returned as the result.
479 assert :: Bool -> a -> a