3 , ForeignFunctionInterface
4 , ExistentialQuantification
9 -----------------------------------------------------------------------------
11 -- Module : Control.OldException
12 -- Copyright : (c) The University of Glasgow 2001
13 -- License : BSD-style (see the file libraries/base/LICENSE)
15 -- Maintainer : libraries@haskell.org
16 -- Stability : experimental
17 -- Portability : non-portable (extended exceptions)
19 -- This module provides support for raising and catching both built-in
20 -- and user-defined exceptions.
22 -- In addition to exceptions thrown by 'IO' operations, exceptions may
23 -- be thrown by pure code (imprecise exceptions) or by external events
24 -- (asynchronous exceptions), but may only be caught in the 'IO' monad.
25 -- For more details, see:
27 -- * /A semantics for imprecise exceptions/, by Simon Peyton Jones,
28 -- Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson,
31 -- * /Asynchronous exceptions in Haskell/, by Simon Marlow, Simon Peyton
32 -- Jones, Andy Moran and John Reppy, in /PLDI'01/.
34 -----------------------------------------------------------------------------
36 module Control.OldException {-# DEPRECATED "Future versions of base will not support the old exceptions style. Please switch to extensible exceptions." #-} (
38 -- * The Exception type
39 Exception(..), -- instance Eq, Ord, Show, Typeable
40 New.IOException, -- instance Eq, Ord, Show, Typeable
41 New.ArithException(..), -- instance Eq, Ord, Show, Typeable
42 New.ArrayException(..), -- instance Eq, Ord, Show, Typeable
43 New.AsyncException(..), -- instance Eq, Ord, Show, Typeable
45 -- * Throwing exceptions
46 throwIO, -- :: Exception -> IO a
47 throw, -- :: Exception -> a
48 ioError, -- :: IOError -> IO a
49 #ifdef __GLASGOW_HASKELL__
50 -- XXX Need to restrict the type of this:
51 New.throwTo, -- :: ThreadId -> Exception -> a
54 -- * Catching Exceptions
56 -- |There are several functions for catching and examining
57 -- exceptions; all of them may only be used from within the
60 -- ** The @catch@ functions
61 catch, -- :: IO a -> (Exception -> IO a) -> IO a
62 catchJust, -- :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a
64 -- ** The @handle@ functions
65 handle, -- :: (Exception -> IO a) -> IO a -> IO a
66 handleJust,-- :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
68 -- ** The @try@ functions
69 try, -- :: IO a -> IO (Either Exception a)
70 tryJust, -- :: (Exception -> Maybe b) -> a -> IO (Either b a)
72 -- ** The @evaluate@ function
73 evaluate, -- :: a -> IO a
75 -- ** The @mapException@ function
76 mapException, -- :: (Exception -> Exception) -> a -> a
78 -- ** Exception predicates
82 ioErrors, -- :: Exception -> Maybe IOError
83 arithExceptions, -- :: Exception -> Maybe ArithException
84 errorCalls, -- :: Exception -> Maybe String
85 dynExceptions, -- :: Exception -> Maybe Dynamic
86 assertions, -- :: Exception -> Maybe String
87 asyncExceptions, -- :: Exception -> Maybe AsyncException
88 userErrors, -- :: Exception -> Maybe String
90 -- * Dynamic exceptions
93 throwDyn, -- :: Typeable ex => ex -> b
94 #ifdef __GLASGOW_HASKELL__
95 throwDynTo, -- :: Typeable ex => ThreadId -> ex -> b
97 catchDyn, -- :: Typeable ex => IO a -> (ex -> IO a) -> IO a
99 -- * Asynchronous Exceptions
103 -- ** Asynchronous exception control
105 -- |The following two functions allow a thread to control delivery of
106 -- asynchronous exceptions during a critical region.
108 block, -- :: IO a -> IO a
109 unblock, -- :: IO a -> IO a
111 -- *** Applying @block@ to an exception handler
115 -- *** Interruptible operations
121 assert, -- :: Bool -> a -> a
125 bracket, -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO ()
126 bracket_, -- :: IO a -> IO b -> IO c -> IO ()
129 finally, -- :: IO a -> IO b -> IO a
131 #ifdef __GLASGOW_HASKELL__
132 setUncaughtExceptionHandler, -- :: (Exception -> IO ()) -> IO ()
133 getUncaughtExceptionHandler -- :: IO (Exception -> IO ())
137 #ifdef __GLASGOW_HASKELL__
140 -- import GHC.IO ( IO )
141 import GHC.IO.Handle.FD ( stdout )
142 import qualified GHC.IO as New
143 import qualified GHC.IO.Exception as New
144 import GHC.Conc hiding (setUncaughtExceptionHandler,
145 getUncaughtExceptionHandler)
146 import Data.IORef ( IORef, newIORef, readIORef, writeIORef )
147 import Foreign.C.String ( CString, withCString )
148 import GHC.IO.Handle ( hFlush )
152 import Prelude hiding (catch)
153 import Hugs.Prelude as New (ExitCode(..))
156 import qualified Control.Exception as New
157 import Control.Exception ( toException, fromException, throw, block, unblock, mask, evaluate, throwIO )
158 import System.IO.Error hiding ( catch, try )
159 import System.IO.Unsafe (unsafePerformIO)
165 import System.IO.Error (catch, ioError)
167 import DIOError -- defn of IOError type
169 -- minimum needed for nhc98 to pretend it has Exceptions
170 type Exception = IOError
171 type IOException = IOError
176 throwIO :: Exception -> IO a
178 throw :: Exception -> a
179 throw = unsafePerformIO . throwIO
181 evaluate :: a -> IO a
182 evaluate x = x `seq` return x
184 ioErrors :: Exception -> Maybe IOError
186 arithExceptions :: Exception -> Maybe ArithException
187 arithExceptions = const Nothing
188 errorCalls :: Exception -> Maybe String
189 errorCalls = const Nothing
190 dynExceptions :: Exception -> Maybe Dynamic
191 dynExceptions = const Nothing
192 assertions :: Exception -> Maybe String
193 assertions = const Nothing
194 asyncExceptions :: Exception -> Maybe AsyncException
195 asyncExceptions = const Nothing
196 userErrors :: Exception -> Maybe String
197 userErrors (UserError _ s) = Just s
198 userErrors _ = Nothing
200 block :: IO a -> IO a
202 unblock :: IO a -> IO a
205 assert :: Bool -> a -> a
207 assert False _ = throw (UserError "" "Assertion failed")
210 -----------------------------------------------------------------------------
211 -- Catching exceptions
213 -- |This is the simplest of the exception-catching functions. It
214 -- takes a single argument, runs it, and if an exception is raised
215 -- the \"handler\" is executed, with the value of the exception passed as an
216 -- argument. Otherwise, the result is returned as normal. For example:
218 -- > catch (openFile f ReadMode)
219 -- > (\e -> hPutStr stderr ("Couldn't open "++f++": " ++ show e))
221 -- For catching exceptions in pure (non-'IO') expressions, see the
222 -- function 'evaluate'.
224 -- Note that due to Haskell\'s unspecified evaluation order, an
225 -- expression may return one of several possible exceptions: consider
226 -- the expression @error \"urk\" + 1 \`div\` 0@. Does
227 -- 'catch' execute the handler passing
228 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
230 -- The answer is \"either\": 'catch' makes a
231 -- non-deterministic choice about which exception to catch. If you
232 -- call it again, you might get a different exception back. This is
233 -- ok, because 'catch' is an 'IO' computation.
235 -- Note that 'catch' catches all types of exceptions, and is generally
236 -- used for \"cleaning up\" before passing on the exception using
237 -- 'throwIO'. It is not good practice to discard the exception and
238 -- continue, without first checking the type of the exception (it
239 -- might be a 'ThreadKilled', for example). In this case it is usually better
240 -- to use 'catchJust' and select the kinds of exceptions to catch.
242 -- Also note that the "Prelude" also exports a function called
243 -- 'Prelude.catch' with a similar type to 'Control.OldException.catch',
244 -- except that the "Prelude" version only catches the IO and user
245 -- families of exceptions (as required by Haskell 98).
247 -- We recommend either hiding the "Prelude" version of 'Prelude.catch'
248 -- when importing "Control.OldException":
250 -- > import Prelude hiding (catch)
252 -- or importing "Control.OldException" qualified, to avoid name-clashes:
254 -- > import qualified Control.OldException as C
256 -- and then using @C.catch@
259 catch :: IO a -- ^ The computation to run
260 -> (Exception -> IO a) -- ^ Handler to invoke if an exception is raised
262 -- note: bundling the exceptions is done in the New.Exception
263 -- instance of Exception; see below.
266 -- | The function 'catchJust' is like 'catch', but it takes an extra
267 -- argument which is an /exception predicate/, a function which
268 -- selects which type of exceptions we\'re interested in. There are
269 -- some predefined exception predicates for useful subsets of
270 -- exceptions: 'ioErrors', 'arithExceptions', and so on. For example,
271 -- to catch just calls to the 'error' function, we could use
273 -- > result <- catchJust errorCalls thing_to_try handler
275 -- Any other exceptions which are not matched by the predicate
276 -- are re-raised, and may be caught by an enclosing
277 -- 'catch' or 'catchJust'.
279 :: (Exception -> 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 -> IO a) -> IO a -> IO a
296 -- | A version of 'catchJust' with the arguments swapped around (see
298 handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
299 handleJust p = flip (catchJust p)
301 -----------------------------------------------------------------------------
304 -- | This function maps one exception into another as proposed in the
305 -- paper \"A semantics for imprecise exceptions\".
307 -- Notice that the usage of 'unsafePerformIO' is safe here.
309 mapException :: (Exception -> Exception) -> a -> a
310 mapException f v = unsafePerformIO (catch (evaluate v)
313 -----------------------------------------------------------------------------
314 -- 'try' and variations.
316 -- | Similar to 'catch', but returns an 'Either' result which is
317 -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an
318 -- exception was raised and its value is @e@.
320 -- > try a = catch (Right `liftM` a) (return . Left)
322 -- Note: as with 'catch', it is only polite to use this variant if you intend
323 -- to re-throw the exception after performing whatever cleanup is needed.
324 -- Otherwise, 'tryJust' is generally considered to be better.
326 -- Also note that "System.IO.Error" also exports a function called
327 -- 'System.IO.Error.try' with a similar type to 'Control.OldException.try',
328 -- except that it catches only the IO and user families of exceptions
329 -- (as required by the Haskell 98 @IO@ module).
331 try :: IO a -> IO (Either Exception a)
332 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
334 -- | A variant of 'try' that takes an exception predicate to select
335 -- which exceptions are caught (c.f. 'catchJust'). If the exception
336 -- does not match the predicate, it is re-thrown.
337 tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a)
341 Right v -> return (Right v)
342 Left e -> case p e of
344 Just b -> return (Left b)
346 -----------------------------------------------------------------------------
347 -- Dynamic exceptions
350 -- #DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an
351 -- interface for throwing and catching exceptions of type 'Dynamic'
352 -- (see "Data.Dynamic") which allows exception values of any type in
353 -- the 'Typeable' class to be thrown and caught.
355 -- | Raise any value as an exception, provided it is in the
357 throwDyn :: Typeable exception => exception -> b
359 throwDyn exception = throw (UserError "" "dynamic exception")
361 throwDyn exception = throw (DynException (toDyn exception))
364 #ifdef __GLASGOW_HASKELL__
365 -- | A variant of 'throwDyn' that throws the dynamic exception to an
366 -- arbitrary thread (GHC only: c.f. 'throwTo').
367 throwDynTo :: Typeable exception => ThreadId -> exception -> IO ()
368 throwDynTo t exception = New.throwTo t (DynException (toDyn exception))
369 #endif /* __GLASGOW_HASKELL__ */
371 -- | Catch dynamic exceptions of the required type. All other
372 -- exceptions are re-thrown, including dynamic exceptions of the wrong
375 -- When using dynamic exceptions it is advisable to define a new
376 -- datatype to use for your exception type, to avoid possible clashes
377 -- with dynamic exceptions used in other libraries.
379 catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a
381 catchDyn m k = m -- can't catch dyn exceptions in nhc98
383 catchDyn m k = New.catch m handler
384 where handler ex = case ex of
385 (DynException dyn) ->
386 case fromDynamic dyn of
387 Just exception -> k exception
392 -----------------------------------------------------------------------------
393 -- Exception Predicates
396 -- These pre-defined predicates may be used as the first argument to
397 -- 'catchJust', 'tryJust', or 'handleJust' to select certain common
398 -- classes of exceptions.
400 ioErrors :: Exception -> Maybe IOError
401 arithExceptions :: Exception -> Maybe New.ArithException
402 errorCalls :: Exception -> Maybe String
403 assertions :: Exception -> Maybe String
404 dynExceptions :: Exception -> Maybe Dynamic
405 asyncExceptions :: Exception -> Maybe New.AsyncException
406 userErrors :: Exception -> Maybe String
408 ioErrors (IOException e) = Just e
411 arithExceptions (ArithException e) = Just e
412 arithExceptions _ = Nothing
414 errorCalls (ErrorCall e) = Just e
415 errorCalls _ = Nothing
417 assertions (AssertionFailed e) = Just e
418 assertions _ = Nothing
420 dynExceptions (DynException e) = Just e
421 dynExceptions _ = Nothing
423 asyncExceptions (AsyncException e) = Just e
424 asyncExceptions _ = Nothing
426 userErrors (IOException e) | isUserError e = Just (ioeGetErrorString e)
427 userErrors _ = Nothing
429 -----------------------------------------------------------------------------
430 -- Some Useful Functions
432 -- | When you want to acquire a resource, do some work with it, and
433 -- then release the resource, it is a good idea to use 'bracket',
434 -- because 'bracket' will install the necessary exception handler to
435 -- release the resource in the event that an exception is raised
436 -- during the computation. If an exception is raised, then 'bracket' will
437 -- re-raise the exception (after performing the release).
439 -- A common example is opening a file:
442 -- > (openFile "filename" ReadMode)
444 -- > (\handle -> do { ... })
446 -- The arguments to 'bracket' are in this order so that we can partially apply
449 -- > withFile name mode = bracket (openFile name mode) hClose
453 :: IO a -- ^ computation to run first (\"acquire resource\")
454 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
455 -> (a -> IO c) -- ^ computation to run in-between
456 -> IO c -- returns the value from the in-between computation
457 bracket before after thing =
458 mask $ \restore -> do
462 (\e -> do { _ <- after a; throw e })
467 -- | A specialised variant of 'bracket' with just a computation to run
470 finally :: IO a -- ^ computation to run first
471 -> IO b -- ^ computation to run afterward (even if an exception
473 -> IO a -- returns the value from the first computation
475 mask $ \restore -> do
478 (\e -> do { _ <- sequel; throw e })
482 -- | A variant of 'bracket' where the return value from the first computation
484 bracket_ :: IO a -> IO b -> IO c -> IO c
485 bracket_ before after thing = bracket before (const after) (const thing)
487 -- | Like bracket, but only performs the final action if there was an
488 -- exception raised by the in-between computation.
490 :: IO a -- ^ computation to run first (\"acquire resource\")
491 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
492 -> (a -> IO c) -- ^ computation to run in-between
493 -> IO c -- returns the value from the in-between computation
494 bracketOnError before after thing =
495 mask $ \restore -> do
499 (\e -> do { _ <- after a; throw e })
501 -- -----------------------------------------------------------------------------
502 -- Asynchronous exceptions
506 #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
507 external influences, and can be raised at any point during execution.
508 'StackOverflow' and 'HeapOverflow' are two examples of
509 system-generated asynchronous exceptions.
511 The primary source of asynchronous exceptions, however, is
514 > throwTo :: ThreadId -> Exception -> IO ()
516 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
517 running thread to raise an arbitrary exception in another thread. The
518 exception is therefore asynchronous with respect to the target thread,
519 which could be doing anything at the time it receives the exception.
520 Great care should be taken with asynchronous exceptions; it is all too
521 easy to introduce race conditions by the over zealous use of
526 There\'s an implied 'mask_' around every exception handler in a call
527 to one of the 'catch' family of functions. This is because that is
528 what you want most of the time - it eliminates a common race condition
529 in starting an exception handler, because there may be no exception
530 handler on the stack to handle another exception if one arrives
531 immediately. If asynchronous exceptions are blocked on entering the
532 handler, though, we have time to install a new exception handler
533 before being interrupted. If this weren\'t the default, one would have
534 to write something like
537 > catch (restore (...))
540 If you need to unblock asynchronous exceptions again in the exception
541 handler, just use 'unblock' as normal.
543 Note that 'try' and friends /do not/ have a similar default, because
544 there is no exception handler in this case. If you want to use 'try'
545 in an asynchronous-exception-safe way, you will need to use
551 Some operations are /interruptible/, which means that they can receive
552 asynchronous exceptions even in the scope of a 'mask'. Any function
553 which may itself block is defined as interruptible; this includes
554 'Control.Concurrent.MVar.takeMVar'
555 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
556 and most operations which perform
557 some I\/O with the outside world. The reason for having
558 interruptible operations is so that we can write things like
560 > mask $ \restore -> do
562 > catch (restore (...))
565 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
567 combination could lead to deadlock, because the thread itself would be
568 blocked in a state where it can\'t receive any asynchronous exceptions.
569 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
570 safe in the knowledge that the thread can receive exceptions right up
571 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
572 Similar arguments apply for other interruptible operations like
573 'System.IO.openFile'.
576 #if !(__GLASGOW_HASKELL__ || __NHC__)
577 assert :: Bool -> a -> a
579 assert False _ = throw (AssertionFailed "")
583 #ifdef __GLASGOW_HASKELL__
584 {-# NOINLINE uncaughtExceptionHandler #-}
585 uncaughtExceptionHandler :: IORef (Exception -> IO ())
586 uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler)
588 defaultHandler :: Exception -> IO ()
589 defaultHandler ex = do
590 (hFlush stdout) `New.catchAny` (\ _ -> return ())
592 Deadlock -> "no threads to run: infinite loop or deadlock?"
594 other -> showsPrec 0 other ""
595 withCString "%s" $ \cfmt ->
596 withCString msg $ \cmsg ->
599 -- don't use errorBelch() directly, because we cannot call varargs functions
601 foreign import ccall unsafe "HsBase.h errorBelch2"
602 errorBelch :: CString -> CString -> IO ()
604 setUncaughtExceptionHandler :: (Exception -> IO ()) -> IO ()
605 setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler
607 getUncaughtExceptionHandler :: IO (Exception -> IO ())
608 getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler
611 -- ------------------------------------------------------------------------
612 -- Exception datatype and operations
614 -- |The type of exceptions. Every kind of system-generated exception
615 -- has a constructor in the 'Exception' type, and values of other
616 -- types may be injected into 'Exception' by coercing them to
617 -- 'Data.Dynamic.Dynamic' (see the section on Dynamic Exceptions:
618 -- "Control.OldException\#DynamicExceptions").
620 = ArithException New.ArithException
621 -- ^Exceptions raised by arithmetic
622 -- operations. (NOTE: GHC currently does not throw
623 -- 'ArithException's except for 'DivideByZero').
624 | ArrayException New.ArrayException
625 -- ^Exceptions raised by array-related
626 -- operations. (NOTE: GHC currently does not throw
627 -- 'ArrayException's).
628 | AssertionFailed String
629 -- ^This exception is thrown by the
630 -- 'assert' operation when the condition
631 -- fails. The 'String' argument contains the
632 -- location of the assertion in the source program.
633 | AsyncException New.AsyncException
634 -- ^Asynchronous exceptions (see section on Asynchronous Exceptions: "Control.OldException\#AsynchronousExceptions").
636 -- ^The current thread was executing a call to
637 -- 'Control.Concurrent.MVar.takeMVar' that could never return,
638 -- because there are no other references to this 'MVar'.
639 | BlockedIndefinitely
640 -- ^The current thread was waiting to retry an atomic memory transaction
641 -- that could never become possible to complete because there are no other
642 -- threads referring to any of the TVars involved.
644 -- ^The runtime detected an attempt to nest one STM transaction
645 -- inside another one, presumably due to the use of
646 -- 'unsafePeformIO' with 'atomically'.
648 -- ^There are no runnable threads, so the program is
649 -- deadlocked. The 'Deadlock' exception is
650 -- raised in the main thread only (see also: "Control.Concurrent").
651 | DynException Dynamic
652 -- ^Dynamically typed exceptions (see section on Dynamic Exceptions: "Control.OldException\#DynamicExceptions").
654 -- ^The 'ErrorCall' exception is thrown by 'error'. The 'String'
655 -- argument of 'ErrorCall' is the string passed to 'error' when it was
657 | ExitException New.ExitCode
658 -- ^The 'ExitException' exception is thrown by 'System.Exit.exitWith' (and
659 -- 'System.Exit.exitFailure'). The 'ExitCode' argument is the value passed
660 -- to 'System.Exit.exitWith'. An unhandled 'ExitException' exception in the
661 -- main thread will cause the program to be terminated with the given
663 | IOException New.IOException
664 -- ^These are the standard IO exceptions generated by
665 -- Haskell\'s @IO@ operations. See also "System.IO.Error".
666 | NoMethodError String
667 -- ^An attempt was made to invoke a class method which has
668 -- no definition in this instance, and there was no default
669 -- definition given in the class declaration. GHC issues a
670 -- warning when you compile an instance which has missing
673 -- ^The current thread is stuck in an infinite loop. This
674 -- exception may or may not be thrown when the program is
676 | PatternMatchFail String
677 -- ^A pattern matching failure. The 'String' argument should contain a
678 -- descriptive message including the function name, source file
681 -- ^An attempt was made to evaluate a field of a record
682 -- for which no value was given at construction time. The
683 -- 'String' argument gives the location of the
684 -- record construction in the source program.
686 -- ^A field selection was attempted on a constructor that
687 -- doesn\'t have the requested field. This can happen with
688 -- multi-constructor records when one or more fields are
689 -- missing from some of the constructors. The
690 -- 'String' argument gives the location of the
691 -- record selection in the source program.
693 -- ^An attempt was made to update a field in a record,
694 -- where the record doesn\'t have the requested field. This can
695 -- only occur with multi-constructor records, when one or more
696 -- fields are missing from some of the constructors. The
697 -- 'String' argument gives the location of the
698 -- record update in the source program.
699 INSTANCE_TYPEABLE0(Exception,exceptionTc,"Exception")
701 -- helper type for simplifying the type casting logic below
702 data Caster = forall e . New.Exception e => Caster (e -> Exception)
704 instance New.Exception Exception where
705 -- We need to collect all the sorts of exceptions that used to be
706 -- bundled up into the Exception type, and rebundle them for
708 fromException exc0 = foldr tryCast Nothing casters where
709 tryCast (Caster f) e = case fromException exc0 of
710 Just exc -> Just (f exc)
713 [Caster (\exc -> ArithException exc),
714 Caster (\exc -> ArrayException exc),
715 Caster (\(New.AssertionFailed err) -> AssertionFailed err),
716 Caster (\exc -> AsyncException exc),
717 Caster (\New.BlockedIndefinitelyOnMVar -> BlockedOnDeadMVar),
718 Caster (\New.BlockedIndefinitelyOnSTM -> BlockedIndefinitely),
719 Caster (\New.NestedAtomically -> NestedAtomically),
720 Caster (\New.Deadlock -> Deadlock),
721 Caster (\exc -> DynException exc),
722 Caster (\(New.ErrorCall err) -> ErrorCall err),
723 Caster (\exc -> ExitException exc),
724 Caster (\exc -> IOException exc),
725 Caster (\(New.NoMethodError err) -> NoMethodError err),
726 Caster (\New.NonTermination -> NonTermination),
727 Caster (\(New.PatternMatchFail err) -> PatternMatchFail err),
728 Caster (\(New.RecConError err) -> RecConError err),
729 Caster (\(New.RecSelError err) -> RecSelError err),
730 Caster (\(New.RecUpdError err) -> RecUpdError err),
731 -- Anything else gets taken as a Dynamic exception. It's
732 -- important that we put all exceptions into the old Exception
733 -- type somehow, or throwing a new exception wouldn't cause
734 -- the cleanup code for bracket, finally etc to happen.
735 Caster (\exc -> DynException (toDyn (exc :: New.SomeException)))]
737 -- Unbundle exceptions.
738 toException (ArithException exc) = toException exc
739 toException (ArrayException exc) = toException exc
740 toException (AssertionFailed err) = toException (New.AssertionFailed err)
741 toException (AsyncException exc) = toException exc
742 toException BlockedOnDeadMVar = toException New.BlockedIndefinitelyOnMVar
743 toException BlockedIndefinitely = toException New.BlockedIndefinitelyOnSTM
744 toException NestedAtomically = toException New.NestedAtomically
745 toException Deadlock = toException New.Deadlock
746 -- If a dynamic exception is a SomeException then resurrect it, so
747 -- that bracket, catch+throw etc rethrow the same exception even
748 -- when the exception is in the new style.
749 -- If it's not a SomeException, then just throw the Dynamic.
750 toException (DynException exc) = case fromDynamic exc of
752 Nothing -> toException exc
753 toException (ErrorCall err) = toException (New.ErrorCall err)
754 toException (ExitException exc) = toException exc
755 toException (IOException exc) = toException exc
756 toException (NoMethodError err) = toException (New.NoMethodError err)
757 toException NonTermination = toException New.NonTermination
758 toException (PatternMatchFail err) = toException (New.PatternMatchFail err)
759 toException (RecConError err) = toException (New.RecConError err)
760 toException (RecSelError err) = toException (New.RecSelError err)
761 toException (RecUpdError err) = toException (New.RecUpdError err)
763 instance Show Exception where
764 showsPrec _ (IOException err) = shows err
765 showsPrec _ (ArithException err) = shows err
766 showsPrec _ (ArrayException err) = shows err
767 showsPrec _ (ErrorCall err) = showString err
768 showsPrec _ (ExitException err) = showString "exit: " . shows err
769 showsPrec _ (NoMethodError err) = showString err
770 showsPrec _ (PatternMatchFail err) = showString err
771 showsPrec _ (RecSelError err) = showString err
772 showsPrec _ (RecConError err) = showString err
773 showsPrec _ (RecUpdError err) = showString err
774 showsPrec _ (AssertionFailed err) = showString err
775 showsPrec _ (DynException err) = showString "exception :: " . showsTypeRep (dynTypeRep err)
776 showsPrec _ (AsyncException e) = shows e
777 showsPrec p BlockedOnDeadMVar = showsPrec p New.BlockedIndefinitelyOnMVar
778 showsPrec p BlockedIndefinitely = showsPrec p New.BlockedIndefinitelyOnSTM
779 showsPrec p NestedAtomically = showsPrec p New.NestedAtomically
780 showsPrec p NonTermination = showsPrec p New.NonTermination
781 showsPrec p Deadlock = showsPrec p New.Deadlock
783 instance Eq Exception where
784 IOException e1 == IOException e2 = e1 == e2
785 ArithException e1 == ArithException e2 = e1 == e2
786 ArrayException e1 == ArrayException e2 = e1 == e2
787 ErrorCall e1 == ErrorCall e2 = e1 == e2
788 ExitException e1 == ExitException e2 = e1 == e2
789 NoMethodError e1 == NoMethodError e2 = e1 == e2
790 PatternMatchFail e1 == PatternMatchFail e2 = e1 == e2
791 RecSelError e1 == RecSelError e2 = e1 == e2
792 RecConError e1 == RecConError e2 = e1 == e2
793 RecUpdError e1 == RecUpdError e2 = e1 == e2
794 AssertionFailed e1 == AssertionFailed e2 = e1 == e2
795 DynException _ == DynException _ = False -- incomparable
796 AsyncException e1 == AsyncException e2 = e1 == e2
797 BlockedOnDeadMVar == BlockedOnDeadMVar = True
798 NonTermination == NonTermination = True
799 NestedAtomically == NestedAtomically = True
800 Deadlock == Deadlock = True