1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2 -----------------------------------------------------------------------------
4 -- Module : Control.Exception
5 -- Copyright : (c) The University of Glasgow 2001
6 -- License : BSD-style (see the file libraries/base/LICENSE)
8 -- Maintainer : libraries@haskell.org
9 -- Stability : experimental
10 -- Portability : non-portable (extended exceptions)
12 -- This module provides support for raising and catching both built-in
13 -- and user-defined exceptions.
15 -- In addition to exceptions thrown by 'IO' operations, exceptions may
16 -- be thrown by pure code (imprecise exceptions) or by external events
17 -- (asynchronous exceptions), but may only be caught in the 'IO' monad.
18 -- For more details, see:
20 -- * /A semantics for imprecise exceptions/, by Simon Peyton Jones,
21 -- Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson,
24 -- * /Asynchronous exceptions in Haskell/, by Simon Marlow, Simon Peyton
25 -- Jones, Andy Moran and John Reppy, in /PLDI'01/.
27 -----------------------------------------------------------------------------
29 module Control.Exception (
31 -- * The Exception type
33 Exception(..), -- instance Eq, Ord, Show, Typeable
34 IOException, -- instance Eq, Ord, Show, Typeable
35 ArithException(..), -- instance Eq, Ord, Show, Typeable
36 ArrayException(..), -- instance Eq, Ord, Show, Typeable
38 AsyncException(..), -- instance Eq, Ord, Show, Typeable
39 NonTermination(..), nonTermination,
40 BlockedOnDeadMVar(..),
41 BlockedIndefinitely(..),
42 NestedAtomically(..), nestedAtomically,
50 -- * Throwing exceptions
51 throwIO, -- :: Exception -> IO a
52 throw, -- :: Exception -> a
53 ioError, -- :: IOError -> IO a
54 #ifdef __GLASGOW_HASKELL__
55 throwTo, -- :: ThreadId -> Exception -> a
58 -- * Catching Exceptions
60 -- |There are several functions for catching and examining
61 -- exceptions; all of them may only be used from within the
64 -- ** The @catch@ functions
65 catch, -- :: IO a -> (Exception -> IO a) -> IO a
68 catchJust, -- :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a
70 -- ** The @handle@ functions
71 handle, -- :: (Exception -> IO a) -> IO a -> IO a
73 handleJust,-- :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
75 -- ** The @try@ functions
76 try, -- :: IO a -> IO (Either Exception a)
77 tryJust, -- :: (Exception -> Maybe b) -> a -> IO (Either b a)
81 -- ** The @evaluate@ function
82 evaluate, -- :: a -> IO a
84 -- ** The @mapException@ function
85 mapException, -- :: (Exception -> Exception) -> a -> a
87 -- * Asynchronous Exceptions
91 -- ** Asynchronous exception control
93 -- |The following two functions allow a thread to control delivery of
94 -- asynchronous exceptions during a critical region.
96 block, -- :: IO a -> IO a
97 unblock, -- :: IO a -> IO a
98 blocked, -- :: IO Bool
100 -- *** Applying @block@ to an exception handler
104 -- *** Interruptible operations
110 assert, -- :: Bool -> a -> a
114 bracket, -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO ()
115 bracket_, -- :: IO a -> IO b -> IO c -> IO ()
118 finally, -- :: IO a -> IO b -> IO a
120 recSelError, recConError, irrefutPatError, runtimeError,
121 nonExhaustiveGuardsError, patError, noMethodBindingError,
123 #ifdef __GLASGOW_HASKELL__
124 setUncaughtExceptionHandler, -- :: (Exception -> IO ()) -> IO ()
125 getUncaughtExceptionHandler -- :: IO (Exception -> IO ())
129 #ifdef __GLASGOW_HASKELL__
132 import {-# SOURCE #-} GHC.Handle
136 import GHC.IOBase as ExceptionBase
137 import GHC.Exception hiding ( Exception )
138 import {-# SOURCE #-} GHC.Conc ( ThreadId(ThreadId) )
139 import Foreign.C.String ( CString, withCString )
143 import Hugs.Exception as ExceptionBase
151 import qualified System.IO.Error as H'98 (catch)
152 import System.IO.Error (ioError)
154 import DIOError -- defn of IOError type
155 import System (ExitCode())
157 -- minimum needed for nhc98 to pretend it has Exceptions
158 data Exception = IOException IOException
159 | ArithException ArithException
160 | ArrayException ArrayException
161 | AsyncException AsyncException
162 | ExitException ExitCode
164 type IOException = IOError
168 instance Show ArithException
169 instance Show ArrayException
170 instance Show AsyncException
172 catch :: IO a -> (Exception -> IO a) -> IO a
173 a `catch` b = a `H'98.catch` (b . IOException)
175 throwIO :: Exception -> IO a
176 throwIO (IOException e) = ioError e
177 throwIO _ = ioError (UserError "Control.Exception.throwIO"
179 throw :: Exception -> a
180 throw = unsafePerformIO . throwIO
182 evaluate :: a -> IO a
183 evaluate x = x `seq` return x
185 assert :: Bool -> a -> a
187 assert False _ = throw (IOException (UserError "" "Assertion failed"))
190 #ifndef __GLASGOW_HASKELL__
191 -- Dummy definitions for implementations lacking asynchonous exceptions
193 block :: IO a -> IO a
195 unblock :: IO a -> IO a
198 blocked = return False
201 -----------------------------------------------------------------------------
202 -- Catching exceptions
204 -- |This is the simplest of the exception-catching functions. It
205 -- takes a single argument, runs it, and if an exception is raised
206 -- the \"handler\" is executed, with the value of the exception passed as an
207 -- argument. Otherwise, the result is returned as normal. For example:
209 -- > catch (openFile f ReadMode)
210 -- > (\e -> hPutStr stderr ("Couldn't open "++f++": " ++ show e))
212 -- For catching exceptions in pure (non-'IO') expressions, see the
213 -- function 'evaluate'.
215 -- Note that due to Haskell\'s unspecified evaluation order, an
216 -- expression may return one of several possible exceptions: consider
217 -- the expression @error \"urk\" + 1 \`div\` 0@. Does
218 -- 'catch' execute the handler passing
219 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
221 -- The answer is \"either\": 'catch' makes a
222 -- non-deterministic choice about which exception to catch. If you
223 -- call it again, you might get a different exception back. This is
224 -- ok, because 'catch' is an 'IO' computation.
226 -- Note that 'catch' catches all types of exceptions, and is generally
227 -- used for \"cleaning up\" before passing on the exception using
228 -- 'throwIO'. It is not good practice to discard the exception and
229 -- continue, without first checking the type of the exception (it
230 -- might be a 'ThreadKilled', for example). In this case it is usually better
231 -- to use 'catchJust' and select the kinds of exceptions to catch.
233 -- Also note that the "Prelude" also exports a function called
234 -- 'Prelude.catch' with a similar type to 'Control.Exception.catch',
235 -- except that the "Prelude" version only catches the IO and user
236 -- families of exceptions (as required by Haskell 98).
238 -- We recommend either hiding the "Prelude" version of 'Prelude.catch'
239 -- when importing "Control.Exception":
241 -- > import Prelude hiding (catch)
243 -- or importing "Control.Exception" qualified, to avoid name-clashes:
245 -- > import qualified Control.Exception as C
247 -- and then using @C.catch@
251 => IO a -- ^ The computation to run
252 -> (e -> IO a) -- ^ Handler to invoke if an exception is raised
254 catch = ExceptionBase.catchException
256 catches :: IO a -> [Handler a] -> IO a
257 catches io handlers = io `catch` catchesHandler handlers
259 catchesHandler :: [Handler a] -> SomeException -> IO a
260 catchesHandler handlers e = foldr tryHandler (throw e) handlers
261 where tryHandler (Handler handler) res
262 = case fromException e of
263 Just e' -> handler e'
266 data Handler a = forall e . Exception e => Handler (e -> IO a)
268 -- | The function 'catchJust' is like 'catch', but it takes an extra
269 -- argument which is an /exception predicate/, a function which
270 -- selects which type of exceptions we\'re interested in.
272 -- > result <- catchJust errorCalls thing_to_try handler
274 -- Any other exceptions which are not matched by the predicate
275 -- are re-raised, and may be caught by an enclosing
276 -- 'catch' or 'catchJust'.
279 => (e -> Maybe b) -- ^ Predicate to select exceptions
280 -> IO a -- ^ Computation to run
281 -> (b -> IO a) -- ^ Handler
283 catchJust p a handler = catch a handler'
284 where handler' e = case p e of
288 -- | A version of 'catch' with the arguments swapped around; useful in
289 -- situations where the code for the handler is shorter. For example:
291 -- > do handle (\e -> exitWith (ExitFailure 1)) $
293 handle :: Exception e => (e -> IO a) -> IO a -> IO a
296 handleAny :: (forall e . Exception e => e -> IO a) -> IO a -> IO a
297 handleAny = flip catchAny
299 -- | A version of 'catchJust' with the arguments swapped around (see
301 handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a
302 handleJust p = flip (catchJust p)
304 -----------------------------------------------------------------------------
307 -- | This function maps one exception into another as proposed in the
308 -- paper \"A semantics for imprecise exceptions\".
310 -- Notice that the usage of 'unsafePerformIO' is safe here.
312 mapException :: Exception e => (e -> e) -> a -> a
313 mapException f v = unsafePerformIO (catch (evaluate v)
316 -----------------------------------------------------------------------------
317 -- 'try' and variations.
319 -- | Similar to 'catch', but returns an 'Either' result which is
320 -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an
321 -- exception was raised and its value is @e@.
323 -- > try a = catch (Right `liftM` a) (return . Left)
325 -- Note: as with 'catch', it is only polite to use this variant if you intend
326 -- to re-throw the exception after performing whatever cleanup is needed.
327 -- Otherwise, 'tryJust' is generally considered to be better.
329 -- Also note that "System.IO.Error" also exports a function called
330 -- 'System.IO.Error.try' with a similar type to 'Control.Exception.try',
331 -- except that it catches only the IO and user families of exceptions
332 -- (as required by the Haskell 98 @IO@ module).
334 try :: Exception e => IO a -> IO (Either e a)
335 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
337 -- | A variant of 'try' that takes an exception predicate to select
338 -- which exceptions are caught (c.f. 'catchJust'). If the exception
339 -- does not match the predicate, it is re-thrown.
340 tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)
344 Right v -> return (Right v)
345 Left e -> case p e of
347 Just b -> return (Left b)
349 ignoreExceptions :: IO () -> IO ()
350 ignoreExceptions io = io `catchAny` \_ -> return ()
352 onException :: IO a -> IO () -> IO a
353 onException io what = io `catch` \e -> do what
354 throw (e :: SomeException)
356 -----------------------------------------------------------------------------
357 -- Some Useful Functions
359 -- | When you want to acquire a resource, do some work with it, and
360 -- then release the resource, it is a good idea to use 'bracket',
361 -- because 'bracket' will install the necessary exception handler to
362 -- release the resource in the event that an exception is raised
363 -- during the computation. If an exception is raised, then 'bracket' will
364 -- re-raise the exception (after performing the release).
366 -- A common example is opening a file:
369 -- > (openFile "filename" ReadMode)
371 -- > (\handle -> do { ... })
373 -- The arguments to 'bracket' are in this order so that we can partially apply
376 -- > withFile name mode = bracket (openFile name mode) hClose
380 :: IO a -- ^ computation to run first (\"acquire resource\")
381 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
382 -> (a -> IO c) -- ^ computation to run in-between
383 -> IO c -- returns the value from the in-between computation
384 bracket before after thing =
389 (\e -> do { after a; throw e })
395 -- | A specialised variant of 'bracket' with just a computation to run
398 finally :: IO a -- ^ computation to run first
399 -> IO b -- ^ computation to run afterward (even if an exception
401 -> IO a -- returns the value from the first computation
406 (\e -> do { sequel; throw e })
411 -- | A variant of 'bracket' where the return value from the first computation
413 bracket_ :: IO a -> IO b -> IO c -> IO c
414 bracket_ before after thing = bracket before (const after) (const thing)
416 -- | Like bracket, but only performs the final action if there was an
417 -- exception raised by the in-between computation.
419 :: IO a -- ^ computation to run first (\"acquire resource\")
420 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
421 -> (a -> IO c) -- ^ computation to run in-between
422 -> IO c -- returns the value from the in-between computation
423 bracketOnError before after thing =
428 (\e -> do { after a; throw e })
431 -- -----------------------------------------------------------------------------
432 -- Asynchronous exceptions
436 #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
437 external influences, and can be raised at any point during execution.
438 'StackOverflow' and 'HeapOverflow' are two examples of
439 system-generated asynchronous exceptions.
441 The primary source of asynchronous exceptions, however, is
444 > throwTo :: ThreadId -> Exception -> IO ()
446 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
447 running thread to raise an arbitrary exception in another thread. The
448 exception is therefore asynchronous with respect to the target thread,
449 which could be doing anything at the time it receives the exception.
450 Great care should be taken with asynchronous exceptions; it is all too
451 easy to introduce race conditions by the over zealous use of
456 There\'s an implied 'block' around every exception handler in a call
457 to one of the 'catch' family of functions. This is because that is
458 what you want most of the time - it eliminates a common race condition
459 in starting an exception handler, because there may be no exception
460 handler on the stack to handle another exception if one arrives
461 immediately. If asynchronous exceptions are blocked on entering the
462 handler, though, we have time to install a new exception handler
463 before being interrupted. If this weren\'t the default, one would have
464 to write something like
467 > catch (unblock (...))
471 If you need to unblock asynchronous exceptions again in the exception
472 handler, just use 'unblock' as normal.
474 Note that 'try' and friends /do not/ have a similar default, because
475 there is no exception handler in this case. If you want to use 'try'
476 in an asynchronous-exception-safe way, you will need to use
482 Some operations are /interruptible/, which means that they can receive
483 asynchronous exceptions even in the scope of a 'block'. Any function
484 which may itself block is defined as interruptible; this includes
485 'Control.Concurrent.MVar.takeMVar'
486 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
487 and most operations which perform
488 some I\/O with the outside world. The reason for having
489 interruptible operations is so that we can write things like
493 > catch (unblock (...))
497 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
499 combination could lead to deadlock, because the thread itself would be
500 blocked in a state where it can\'t receive any asynchronous exceptions.
501 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
502 safe in the knowledge that the thread can receive exceptions right up
503 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
504 Similar arguments apply for other interruptible operations like
505 'System.IO.openFile'.
508 #if !(__GLASGOW_HASKELL__ || __NHC__)
509 assert :: Bool -> a -> a
511 assert False _ = throw (AssertionFailed "")
515 #ifdef __GLASGOW_HASKELL__
516 {-# NOINLINE uncaughtExceptionHandler #-}
517 uncaughtExceptionHandler :: IORef (SomeException -> IO ())
518 uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler)
520 defaultHandler :: SomeException -> IO ()
521 defaultHandler se@(SomeException ex) = do
522 (hFlush stdout) `catchAny` (\ _ -> return ())
523 let msg = case cast ex of
524 Just Deadlock -> "no threads to run: infinite loop or deadlock?"
526 Just (ErrorCall s) -> s
527 _ -> showsPrec 0 se ""
528 withCString "%s" $ \cfmt ->
529 withCString msg $ \cmsg ->
532 -- don't use errorBelch() directly, because we cannot call varargs functions
534 foreign import ccall unsafe "HsBase.h errorBelch2"
535 errorBelch :: CString -> CString -> IO ()
537 setUncaughtExceptionHandler :: (SomeException -> IO ()) -> IO ()
538 setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler
540 getUncaughtExceptionHandler :: IO (SomeException -> IO ())
541 getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler
544 recSelError, recConError, irrefutPatError, runtimeError,
545 nonExhaustiveGuardsError, patError, noMethodBindingError
546 :: Addr# -> a -- All take a UTF8-encoded C string
548 recSelError s = throw (RecSelError (unpackCStringUtf8# s)) -- No location info unfortunately
549 runtimeError s = error (unpackCStringUtf8# s) -- No location info unfortunately
551 nonExhaustiveGuardsError s = throw (PatternMatchFail (untangle s "Non-exhaustive guards in"))
552 irrefutPatError s = throw (PatternMatchFail (untangle s "Irrefutable pattern failed for pattern"))
553 recConError s = throw (RecConError (untangle s "Missing field in record construction"))
554 noMethodBindingError s = throw (NoMethodError (untangle s "No instance nor default method for class operation"))
555 patError s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))
559 data PatternMatchFail = PatternMatchFail String
562 instance Exception PatternMatchFail
564 instance Show PatternMatchFail where
565 showsPrec _ (PatternMatchFail err) = showString err
569 data RecSelError = RecSelError String
572 instance Exception RecSelError
574 instance Show RecSelError where
575 showsPrec _ (RecSelError err) = showString err
579 data RecConError = RecConError String
582 instance Exception RecConError
584 instance Show RecConError where
585 showsPrec _ (RecConError err) = showString err
589 data RecUpdError = RecUpdError String
592 instance Exception RecUpdError
594 instance Show RecUpdError where
595 showsPrec _ (RecUpdError err) = showString err
599 data NoMethodError = NoMethodError String
602 instance Exception NoMethodError
604 instance Show NoMethodError where
605 showsPrec _ (NoMethodError err) = showString err
609 data AssertionFailed = AssertionFailed String
612 instance Exception AssertionFailed
614 instance Show AssertionFailed where
615 showsPrec _ (AssertionFailed err) = showString err
619 data NonTermination = NonTermination
622 instance Exception NonTermination
624 instance Show NonTermination where
625 showsPrec _ NonTermination = showString "<<loop>>"
627 -- GHC's RTS calls this
628 nonTermination :: SomeException
629 nonTermination = toException NonTermination
633 data Deadlock = Deadlock
636 instance Exception Deadlock
638 instance Show Deadlock where
639 showsPrec _ Deadlock = showString "<<deadlock>>"
643 data NestedAtomically = NestedAtomically
646 instance Exception NestedAtomically
648 instance Show NestedAtomically where
649 showsPrec _ NestedAtomically = showString "Control.Concurrent.STM.atomically was nested"
651 -- GHC's RTS calls this
652 nestedAtomically :: SomeException
653 nestedAtomically = toException NestedAtomically
657 instance Exception Dynamic
661 assertError :: Addr# -> Bool -> a -> a
662 assertError str pred v
664 | otherwise = throw (AssertionFailed (untangle str "Assertion failed"))
667 (untangle coded message) expects "coded" to be of the form
670 location message details
672 untangle :: Addr# -> String -> String
673 untangle coded message
680 coded_str = unpackCStringUtf8# coded
683 = case (span not_bar coded_str) of { (loc, rest) ->
685 ('|':det) -> (loc, ' ' : det)
691 throwTo :: Exception e => ThreadId -> e -> IO ()
692 throwTo (ThreadId id) ex = IO $ \ s ->
693 case (killThread# id (toException ex) s) of s1 -> (# s1, () #)