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 -> a `seq` (# s, a #)
228 -----------------------------------------------------------------------------
229 -- 'try' and variations.
231 -- | Similar to 'catch', but returns an 'Either' result which is
232 -- @(Right a)@ if no exception was raised, or @(Left e)@ if an
233 -- exception was raised and its value is @e@.
235 -- > try a = catch (Right \`liftM\` a) (return . Left)
237 -- Note: as with 'catch', it is only polite to use this variant if you intend
238 -- to re-throw the exception after performing whatever cleanup is needed.
239 -- Otherwise, 'tryJust' is generally considered to be better.
241 try :: IO a -> IO (Either Exception a)
242 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
244 -- | A variant of 'try' that takes an exception predicate to select
245 -- which exceptions are caught (c.f. 'catchJust'). If the exception
246 -- does not match the predicate, it is re-thrown.
247 tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a)
251 Right v -> return (Right v)
252 Left e -> case p e of
254 Just b -> return (Left b)
256 -----------------------------------------------------------------------------
257 -- Dynamic exceptions
260 -- Because the 'Exception' datatype is not extensible, there is an
261 -- interface for throwing and catching exceptions of type 'Dynamic'
262 -- (see "Data.Dynamic") which allows exception values of any type in
263 -- the 'Typeable' class to be thrown and caught.
265 -- | Raise any value as an exception, provided it is in the
267 throwDyn :: Typeable exception => exception -> b
268 throwDyn exception = throw (DynException (toDyn exception))
270 -- | A variant of 'throwDyn' that throws the dynamic exception to an
271 -- arbitrary thread (c.f. 'throwTo').
272 throwDynTo :: Typeable exception => ThreadId -> exception -> IO ()
273 throwDynTo t exception = throwTo t (DynException (toDyn exception))
275 -- | Catch dynamic exceptions of the required type. All other
276 -- exceptions are re-thrown, including dynamic exceptions of the wrong
279 -- When using dynamic exceptions it is advisable to define a new
280 -- datatype to use for your exception type, to avoid possible clashes
281 -- with dynamic exceptions used in other libraries.
283 catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a
284 catchDyn m k = catchException m handle
285 where handle ex = case ex of
286 (DynException dyn) ->
287 case fromDynamic dyn of
288 Just exception -> k exception
292 -----------------------------------------------------------------------------
293 -- Exception Predicates
296 -- These pre-defined predicates may be used as the first argument to
297 -- 'catchJust', 'tryJust', or 'handleJust' to select certain common
298 -- classes of exceptions.
300 ioErrors :: Exception -> Maybe IOError
301 arithExceptions :: Exception -> Maybe ArithException
302 errorCalls :: Exception -> Maybe String
303 dynExceptions :: Exception -> Maybe Dynamic
304 assertions :: Exception -> Maybe String
305 asyncExceptions :: Exception -> Maybe AsyncException
306 userErrors :: Exception -> Maybe String
308 ioErrors e@(IOException _) = Just e
311 arithExceptions (ArithException e) = Just e
312 arithExceptions _ = Nothing
314 errorCalls (ErrorCall e) = Just e
315 errorCalls _ = Nothing
317 assertions (AssertionFailed e) = Just e
318 assertions _ = Nothing
320 dynExceptions (DynException e) = Just e
321 dynExceptions _ = Nothing
323 asyncExceptions (AsyncException e) = Just e
324 asyncExceptions _ = Nothing
326 userErrors e | isUserError e = Just (ioeGetErrorString e)
327 userErrors _ = Nothing
329 -----------------------------------------------------------------------------
330 -- Some Useful Functions
332 -- | When you want to acquire a resource, do some work with it, and
333 -- then release the resource, it is a good idea to use 'bracket',
334 -- because 'bracket' will install the necessary exception handler to
335 -- release the resource in the event that an exception is raised
336 -- during the computation. If an exception is raised, then 'bracket' will
337 -- re-raise the exception (after performing the release).
339 -- A common example is opening a file:
342 -- > (openFile "filename" ReadMode)
344 -- > (\handle -> do { ... })
346 -- The arguments to 'bracket' are in this order so that we can partially apply
349 -- > withFile name = bracket (openFile name) hClose
352 :: IO a -- ^ computation to run first (\"acquire resource\")
353 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
354 -> (a -> IO c) -- ^ computation to run in-between
355 -> IO c -- returns the value from the in-between computation
356 bracket before after thing =
361 (\e -> do { after a; throw e })
367 -- | A specialised variant of 'bracket' with just a computation to run
370 finally :: IO a -- ^ computation to run first
371 -> IO b -- ^ computation to run afterward (even if an exception
373 -> IO a -- returns the value from the first computation
378 (\e -> do { sequel; throw e })
383 -- | A variant of 'bracket' where the return value from the first computation
385 bracket_ :: IO a -> IO b -> IO c -> IO c
386 bracket_ before after thing = bracket before (const after) (const thing)
388 -- -----------------------------------------------------------------------------
389 -- Asynchronous exceptions
393 Asynchronous exceptions are so-called because they arise due to
394 external influences, and can be raised at any point during execution.
395 'StackOverflow' and 'HeapOverflow' are two examples of
396 system-generated asynchronous exceptions.
398 The primary source of asynchronous exceptions, however, is
401 > throwTo :: ThreadId -> Exception -> IO ()
403 'throwTo' (also 'throwDynTo' and 'Concurrent.killThread') allows one
404 running thread to raise an arbitrary exception in another thread. The
405 exception is therefore asynchronous with respect to the target thread,
406 which could be doing anything at the time it receives the exception.
407 Great care should be taken with asynchronous exceptions; it is all too
408 easy to introduce race conditions by the over zealous use of
413 There\'s an implied 'block' around every exception handler in a call
414 to one of the 'catch' family of functions. This is because that is
415 what you want most of the time - it eliminates a common race condition
416 in starting an exception handler, because there may be no exception
417 handler on the stack to handle another exception if one arrives
418 immediately. If asynchronous exceptions are blocked on entering the
419 handler, though, we have time to install a new exception handler
420 before being interrupted. If this weren\'t the default, one would have
421 to write something like
424 > catch (unblock (...))
428 If you need to unblock asynchronous exceptions again in the exception
429 handler, just use 'unblock' as normal.
431 Note that 'try' and friends /do not/ have a similar default, because
432 there is no exception handler in this case. If you want to use 'try'
433 in an asynchronous-exception-safe way, you will need to use
439 Some operations are /interruptible/, which means that they can receive
440 asynchronous exceptions even in the scope of a 'block'. Any function
441 which may itself block is defined as interruptible; this includes
442 'takeMVar' (but not 'tryTakeMVar'), and most operations which perform
443 some I\/O with the outside world.. The reason for having
444 interruptible operations is so that we can write things like
448 > catch (unblock (...))
452 if the 'takeMVar' was not interruptible, then this particular
453 combination could lead to deadlock, because the thread itself would be
454 blocked in a state where it can\'t receive any asynchronous exceptions.
455 With 'takeMVar' interruptible, however, we can be
456 safe in the knowledge that the thread can receive exceptions right up
457 until the point when the 'takeMVar' succeeds.
458 Similar arguments apply for other interruptible operations like
462 -- -----------------------------------------------------------------------------
466 -- | If the first argument evaluates to 'True', then the result is the
467 -- second argument. Otherwise an 'Assertion' exception is raised,
468 -- containing a 'String' with the source file and line number of the
471 -- Assertions can normally be turned on or off with a compiler flag
472 -- (for GHC, assertions are normally on unless the @-fignore-asserts@
473 -- option is give). When assertions are turned off, the first
474 -- argument to 'assert' is ignored, and the second argument is
475 -- returned as the result.
476 assert :: Bool -> a -> a