1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
5 -----------------------------------------------------------------------------
7 -- Module : Control.Exception
8 -- Copyright : (c) The University of Glasgow 2001
9 -- License : BSD-style (see the file libraries/base/LICENSE)
11 -- Maintainer : libraries@haskell.org
12 -- Stability : experimental
13 -- Portability : non-portable (extended exceptions)
15 -- This module provides support for raising and catching both built-in
16 -- and user-defined exceptions.
18 -- In addition to exceptions thrown by 'IO' operations, exceptions may
19 -- be thrown by pure code (imprecise exceptions) or by external events
20 -- (asynchronous exceptions), but may only be caught in the 'IO' monad.
21 -- For more details, see:
23 -- * /A semantics for imprecise exceptions/, by Simon Peyton Jones,
24 -- Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson,
27 -- * /Asynchronous exceptions in Haskell/, by Simon Marlow, Simon Peyton
28 -- Jones, Andy Moran and John Reppy, in /PLDI'01/.
30 -----------------------------------------------------------------------------
32 module Control.Exception (
34 -- * The Exception type
36 Exception(..), -- instance Eq, Ord, Show, Typeable
37 IOException, -- instance Eq, Ord, Show, Typeable
38 ArithException(..), -- instance Eq, Ord, Show, Typeable
39 ArrayException(..), -- instance Eq, Ord, Show, Typeable
41 AsyncException(..), -- instance Eq, Ord, Show, Typeable
42 NonTermination(..), nonTermination,
43 BlockedOnDeadMVar(..),
44 BlockedIndefinitely(..),
45 NestedAtomically(..), nestedAtomically,
54 -- * Throwing exceptions
55 throwIO, -- :: Exception -> IO a
56 throw, -- :: Exception -> a
57 ioError, -- :: IOError -> IO a
58 #ifdef __GLASGOW_HASKELL__
59 throwTo, -- :: ThreadId -> Exception -> a
62 -- * Catching Exceptions
64 -- |There are several functions for catching and examining
65 -- exceptions; all of them may only be used from within the
68 -- ** The @catch@ functions
69 catch, -- :: IO a -> (Exception -> IO a) -> IO a
72 catchJust, -- :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a
74 -- ** The @handle@ functions
75 handle, -- :: (Exception -> IO a) -> IO a -> IO a
77 handleJust,-- :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
79 -- ** The @try@ functions
80 try, -- :: IO a -> IO (Either Exception a)
81 tryJust, -- :: (Exception -> Maybe b) -> a -> IO (Either b a)
85 -- ** The @evaluate@ function
86 evaluate, -- :: a -> IO a
88 -- ** The @mapException@ function
89 mapException, -- :: (Exception -> Exception) -> a -> 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 recSelError, recConError, irrefutPatError, runtimeError,
125 nonExhaustiveGuardsError, patError, noMethodBindingError,
129 #ifdef __GLASGOW_HASKELL__
135 import GHC.IOBase as ExceptionBase
136 import GHC.Exception hiding ( Exception )
137 import GHC.Conc ( ThreadId(ThreadId) )
138 import Foreign.C.String ( CString, withCString )
142 import Hugs.Exception as ExceptionBase
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 assert :: Bool -> a -> a
186 assert False _ = throw (IOException (UserError "" "Assertion failed"))
189 #ifndef __GLASGOW_HASKELL__
190 -- Dummy definitions for implementations lacking asynchonous exceptions
192 block :: IO a -> IO a
194 unblock :: IO a -> IO a
197 blocked = return False
200 -----------------------------------------------------------------------------
201 -- Catching exceptions
203 -- |This is the simplest of the exception-catching functions. It
204 -- takes a single argument, runs it, and if an exception is raised
205 -- the \"handler\" is executed, with the value of the exception passed as an
206 -- argument. Otherwise, the result is returned as normal. For example:
208 -- > catch (openFile f ReadMode)
209 -- > (\e -> hPutStr stderr ("Couldn't open "++f++": " ++ show e))
211 -- For catching exceptions in pure (non-'IO') expressions, see the
212 -- function 'evaluate'.
214 -- Note that due to Haskell\'s unspecified evaluation order, an
215 -- expression may return one of several possible exceptions: consider
216 -- the expression @error \"urk\" + 1 \`div\` 0@. Does
217 -- 'catch' execute the handler passing
218 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
220 -- The answer is \"either\": 'catch' makes a
221 -- non-deterministic choice about which exception to catch. If you
222 -- call it again, you might get a different exception back. This is
223 -- ok, because 'catch' is an 'IO' computation.
225 -- Note that 'catch' catches all types of exceptions, and is generally
226 -- used for \"cleaning up\" before passing on the exception using
227 -- 'throwIO'. It is not good practice to discard the exception and
228 -- continue, without first checking the type of the exception (it
229 -- might be a 'ThreadKilled', for example). In this case it is usually better
230 -- to use 'catchJust' and select the kinds of exceptions to catch.
232 -- Also note that the "Prelude" also exports a function called
233 -- 'Prelude.catch' with a similar type to 'Control.Exception.catch',
234 -- except that the "Prelude" version only catches the IO and user
235 -- families of exceptions (as required by Haskell 98).
237 -- We recommend either hiding the "Prelude" version of 'Prelude.catch'
238 -- when importing "Control.Exception":
240 -- > import Prelude hiding (catch)
242 -- or importing "Control.Exception" qualified, to avoid name-clashes:
244 -- > import qualified Control.Exception as C
246 -- and then using @C.catch@
250 => IO a -- ^ The computation to run
251 -> (e -> IO a) -- ^ Handler to invoke if an exception is raised
253 catch = ExceptionBase.catchException
255 catches :: IO a -> [Handler a] -> IO a
256 catches io handlers = io `catch` catchesHandler handlers
258 catchesHandler :: [Handler a] -> SomeException -> IO a
259 catchesHandler handlers e = foldr tryHandler (throw e) handlers
260 where tryHandler (Handler handler) res
261 = case fromException e of
262 Just e' -> handler e'
265 data Handler a = forall e . Exception e => Handler (e -> IO a)
267 -- | The function 'catchJust' is like 'catch', but it takes an extra
268 -- argument which is an /exception predicate/, a function which
269 -- selects which type of exceptions we\'re interested in.
271 -- > result <- catchJust errorCalls thing_to_try handler
273 -- Any other exceptions which are not matched by the predicate
274 -- are re-raised, and may be caught by an enclosing
275 -- 'catch' or 'catchJust'.
278 => (e -> Maybe b) -- ^ Predicate to select exceptions
279 -> IO a -- ^ Computation to run
280 -> (b -> IO a) -- ^ Handler
282 catchJust p a handler = catch a handler'
283 where handler' e = case p e of
287 -- | A version of 'catch' with the arguments swapped around; useful in
288 -- situations where the code for the handler is shorter. For example:
290 -- > do handle (\e -> exitWith (ExitFailure 1)) $
292 handle :: Exception e => (e -> IO a) -> IO a -> IO a
295 handleAny :: (forall e . Exception e => e -> IO a) -> IO a -> IO a
296 handleAny = flip catchAny
298 -- | A version of 'catchJust' with the arguments swapped around (see
300 handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a
301 handleJust p = flip (catchJust p)
303 -----------------------------------------------------------------------------
306 -- | This function maps one exception into another as proposed in the
307 -- paper \"A semantics for imprecise exceptions\".
309 -- Notice that the usage of 'unsafePerformIO' is safe here.
311 mapException :: Exception e => (e -> e) -> a -> a
312 mapException f v = unsafePerformIO (catch (evaluate v)
315 -----------------------------------------------------------------------------
316 -- 'try' and variations.
318 -- | Similar to 'catch', but returns an 'Either' result which is
319 -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an
320 -- exception was raised and its value is @e@.
322 -- > try a = catch (Right `liftM` a) (return . Left)
324 -- Note: as with 'catch', it is only polite to use this variant if you intend
325 -- to re-throw the exception after performing whatever cleanup is needed.
326 -- Otherwise, 'tryJust' is generally considered to be better.
328 -- Also note that "System.IO.Error" also exports a function called
329 -- 'System.IO.Error.try' with a similar type to 'Control.Exception.try',
330 -- except that it catches only the IO and user families of exceptions
331 -- (as required by the Haskell 98 @IO@ module).
333 try :: Exception e => IO a -> IO (Either e a)
334 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
336 -- | A variant of 'try' that takes an exception predicate to select
337 -- which exceptions are caught (c.f. 'catchJust'). If the exception
338 -- does not match the predicate, it is re-thrown.
339 tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)
343 Right v -> return (Right v)
344 Left e -> case p e of
346 Just b -> return (Left b)
348 ignoreExceptions :: IO () -> IO ()
349 ignoreExceptions io = io `catchAny` \_ -> return ()
351 onException :: IO a -> IO () -> IO a
352 onException io what = io `catch` \e -> do what
353 throw (e :: SomeException)
355 -----------------------------------------------------------------------------
356 -- Some Useful Functions
358 -- | When you want to acquire a resource, do some work with it, and
359 -- then release the resource, it is a good idea to use 'bracket',
360 -- because 'bracket' will install the necessary exception handler to
361 -- release the resource in the event that an exception is raised
362 -- during the computation. If an exception is raised, then 'bracket' will
363 -- re-raise the exception (after performing the release).
365 -- A common example is opening a file:
368 -- > (openFile "filename" ReadMode)
370 -- > (\handle -> do { ... })
372 -- The arguments to 'bracket' are in this order so that we can partially apply
375 -- > withFile name mode = bracket (openFile name mode) hClose
379 :: IO a -- ^ computation to run first (\"acquire resource\")
380 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
381 -> (a -> IO c) -- ^ computation to run in-between
382 -> IO c -- returns the value from the in-between computation
383 bracket before after thing =
388 (\e -> do { after a; throw e })
394 -- | A specialised variant of 'bracket' with just a computation to run
397 finally :: IO a -- ^ computation to run first
398 -> IO b -- ^ computation to run afterward (even if an exception
400 -> IO a -- returns the value from the first computation
405 (\e -> do { sequel; throw e })
410 -- | A variant of 'bracket' where the return value from the first computation
412 bracket_ :: IO a -> IO b -> IO c -> IO c
413 bracket_ before after thing = bracket before (const after) (const thing)
415 -- | Like bracket, but only performs the final action if there was an
416 -- exception raised by the in-between computation.
418 :: IO a -- ^ computation to run first (\"acquire resource\")
419 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
420 -> (a -> IO c) -- ^ computation to run in-between
421 -> IO c -- returns the value from the in-between computation
422 bracketOnError before after thing =
427 (\e -> do { after a; throw e })
430 -- -----------------------------------------------------------------------------
431 -- Asynchronous exceptions
435 #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
436 external influences, and can be raised at any point during execution.
437 'StackOverflow' and 'HeapOverflow' are two examples of
438 system-generated asynchronous exceptions.
440 The primary source of asynchronous exceptions, however, is
443 > throwTo :: ThreadId -> Exception -> IO ()
445 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
446 running thread to raise an arbitrary exception in another thread. The
447 exception is therefore asynchronous with respect to the target thread,
448 which could be doing anything at the time it receives the exception.
449 Great care should be taken with asynchronous exceptions; it is all too
450 easy to introduce race conditions by the over zealous use of
455 There\'s an implied 'block' around every exception handler in a call
456 to one of the 'catch' family of functions. This is because that is
457 what you want most of the time - it eliminates a common race condition
458 in starting an exception handler, because there may be no exception
459 handler on the stack to handle another exception if one arrives
460 immediately. If asynchronous exceptions are blocked on entering the
461 handler, though, we have time to install a new exception handler
462 before being interrupted. If this weren\'t the default, one would have
463 to write something like
466 > catch (unblock (...))
470 If you need to unblock asynchronous exceptions again in the exception
471 handler, just use 'unblock' as normal.
473 Note that 'try' and friends /do not/ have a similar default, because
474 there is no exception handler in this case. If you want to use 'try'
475 in an asynchronous-exception-safe way, you will need to use
481 Some operations are /interruptible/, which means that they can receive
482 asynchronous exceptions even in the scope of a 'block'. Any function
483 which may itself block is defined as interruptible; this includes
484 'Control.Concurrent.MVar.takeMVar'
485 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
486 and most operations which perform
487 some I\/O with the outside world. The reason for having
488 interruptible operations is so that we can write things like
492 > catch (unblock (...))
496 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
498 combination could lead to deadlock, because the thread itself would be
499 blocked in a state where it can\'t receive any asynchronous exceptions.
500 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
501 safe in the knowledge that the thread can receive exceptions right up
502 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
503 Similar arguments apply for other interruptible operations like
504 'System.IO.openFile'.
507 #if !(__GLASGOW_HASKELL__ || __NHC__)
508 assert :: Bool -> a -> a
510 assert False _ = throw (AssertionFailed "")
513 recSelError, recConError, irrefutPatError, runtimeError,
514 nonExhaustiveGuardsError, patError, noMethodBindingError
515 :: Addr# -> a -- All take a UTF8-encoded C string
517 recSelError s = throw (RecSelError (unpackCStringUtf8# s)) -- No location info unfortunately
518 runtimeError s = error (unpackCStringUtf8# s) -- No location info unfortunately
520 nonExhaustiveGuardsError s = throw (PatternMatchFail (untangle s "Non-exhaustive guards in"))
521 irrefutPatError s = throw (PatternMatchFail (untangle s "Irrefutable pattern failed for pattern"))
522 recConError s = throw (RecConError (untangle s "Missing field in record construction"))
523 noMethodBindingError s = throw (NoMethodError (untangle s "No instance nor default method for class operation"))
524 patError s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))
528 data PatternMatchFail = PatternMatchFail String
529 INSTANCE_TYPEABLE0(PatternMatchFail,patternMatchFailTc,"PatternMatchFail")
531 instance Exception PatternMatchFail
533 instance Show PatternMatchFail where
534 showsPrec _ (PatternMatchFail err) = showString err
538 data RecSelError = RecSelError String
539 INSTANCE_TYPEABLE0(RecSelError,recSelErrorTc,"RecSelError")
541 instance Exception RecSelError
543 instance Show RecSelError where
544 showsPrec _ (RecSelError err) = showString err
548 data RecConError = RecConError String
549 INSTANCE_TYPEABLE0(RecConError,recConErrorTc,"RecConError")
551 instance Exception RecConError
553 instance Show RecConError where
554 showsPrec _ (RecConError err) = showString err
558 data RecUpdError = RecUpdError String
559 INSTANCE_TYPEABLE0(RecUpdError,recUpdErrorTc,"RecUpdError")
561 instance Exception RecUpdError
563 instance Show RecUpdError where
564 showsPrec _ (RecUpdError err) = showString err
568 data NoMethodError = NoMethodError String
569 INSTANCE_TYPEABLE0(NoMethodError,noMethodErrorTc,"NoMethodError")
571 instance Exception NoMethodError
573 instance Show NoMethodError where
574 showsPrec _ (NoMethodError err) = showString err
578 data AssertionFailed = AssertionFailed String
579 INSTANCE_TYPEABLE0(AssertionFailed,assertionFailedTc,"AssertionFailed")
581 instance Exception AssertionFailed
583 instance Show AssertionFailed where
584 showsPrec _ (AssertionFailed err) = showString err
588 data NonTermination = NonTermination
589 INSTANCE_TYPEABLE0(NonTermination,nonTerminationTc,"NonTermination")
591 instance Exception NonTermination
593 instance Show NonTermination where
594 showsPrec _ NonTermination = showString "<<loop>>"
596 -- GHC's RTS calls this
597 nonTermination :: SomeException
598 nonTermination = toException NonTermination
602 data NestedAtomically = NestedAtomically
603 INSTANCE_TYPEABLE0(NestedAtomically,nestedAtomicallyTc,"NestedAtomically")
605 instance Exception NestedAtomically
607 instance Show NestedAtomically where
608 showsPrec _ NestedAtomically = showString "Control.Concurrent.STM.atomically was nested"
610 -- GHC's RTS calls this
611 nestedAtomically :: SomeException
612 nestedAtomically = toException NestedAtomically
616 instance Exception Dynamic
620 assertError :: Addr# -> Bool -> a -> a
621 assertError str pred v
623 | otherwise = throw (AssertionFailed (untangle str "Assertion failed"))
626 (untangle coded message) expects "coded" to be of the form
629 location message details
631 untangle :: Addr# -> String -> String
632 untangle coded message
639 coded_str = unpackCStringUtf8# coded
642 = case (span not_bar coded_str) of { (loc, rest) ->
644 ('|':det) -> (loc, ' ' : det)
650 throwTo :: Exception e => ThreadId -> e -> IO ()
651 throwTo (ThreadId id) ex = IO $ \ s ->
652 case (killThread# id (toException ex) s) of s1 -> (# s1, () #)