Fix oversight in Control.OldException
[ghc-base.git] / Control / OldException.hs
1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2
3 #include "Typeable.h"
4
5 -----------------------------------------------------------------------------
6 -- |
7 -- Module      :  Control.OldException
8 -- Copyright   :  (c) The University of Glasgow 2001
9 -- License     :  BSD-style (see the file libraries/base/LICENSE)
10 -- 
11 -- Maintainer  :  libraries@haskell.org
12 -- Stability   :  experimental
13 -- Portability :  non-portable (extended exceptions)
14 --
15 -- This module provides support for raising and catching both built-in
16 -- and user-defined exceptions.
17 --
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:
22 --
23 --  * /A semantics for imprecise exceptions/, by Simon Peyton Jones,
24 --    Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson,
25 --    in /PLDI'99/.
26 --
27 --  * /Asynchronous exceptions in Haskell/, by Simon Marlow, Simon Peyton
28 --    Jones, Andy Moran and John Reppy, in /PLDI'01/.
29 --
30 -----------------------------------------------------------------------------
31
32 module Control.OldException (
33
34         -- * The Exception type
35         Exception(..),          -- instance Eq, Ord, Show, Typeable
36         New.IOException,        -- instance Eq, Ord, Show, Typeable
37         New.ArithException(..), -- instance Eq, Ord, Show, Typeable
38         New.ArrayException(..), -- instance Eq, Ord, Show, Typeable
39         New.AsyncException(..), -- instance Eq, Ord, Show, Typeable
40
41         -- * Throwing exceptions
42         throwIO,        -- :: Exception -> IO a
43         throw,          -- :: Exception -> a
44         ioError,        -- :: IOError -> IO a
45 #ifdef __GLASGOW_HASKELL__
46         -- XXX Need to restrict the type of this:
47         New.throwTo,        -- :: ThreadId -> Exception -> a
48 #endif
49
50         -- * Catching Exceptions
51
52         -- |There are several functions for catching and examining
53         -- exceptions; all of them may only be used from within the
54         -- 'IO' monad.
55
56         -- ** The @catch@ functions
57         catch,     -- :: IO a -> (Exception -> IO a) -> IO a
58         catchJust, -- :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a
59
60         -- ** The @handle@ functions
61         handle,    -- :: (Exception -> IO a) -> IO a -> IO a
62         handleJust,-- :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
63
64         -- ** The @try@ functions
65         try,       -- :: IO a -> IO (Either Exception a)
66         tryJust,   -- :: (Exception -> Maybe b) -> a    -> IO (Either b a)
67
68         -- ** The @evaluate@ function
69         evaluate,  -- :: a -> IO a
70
71         -- ** The @mapException@ function
72         mapException,           -- :: (Exception -> Exception) -> a -> a
73
74         -- ** Exception predicates
75         
76         -- $preds
77
78         ioErrors,               -- :: Exception -> Maybe IOError
79         arithExceptions,        -- :: Exception -> Maybe ArithException
80         errorCalls,             -- :: Exception -> Maybe String
81         dynExceptions,          -- :: Exception -> Maybe Dynamic
82         assertions,             -- :: Exception -> Maybe String
83         asyncExceptions,        -- :: Exception -> Maybe AsyncException
84         userErrors,             -- :: Exception -> Maybe String
85
86         -- * Dynamic exceptions
87
88         -- $dynamic
89         throwDyn,       -- :: Typeable ex => ex -> b
90 #ifdef __GLASGOW_HASKELL__
91         throwDynTo,     -- :: Typeable ex => ThreadId -> ex -> b
92 #endif
93         catchDyn,       -- :: Typeable ex => IO a -> (ex -> IO a) -> IO a
94         
95         -- * Asynchronous Exceptions
96
97         -- $async
98
99         -- ** Asynchronous exception control
100
101         -- |The following two functions allow a thread to control delivery of
102         -- asynchronous exceptions during a critical region.
103
104         block,          -- :: IO a -> IO a
105         unblock,        -- :: IO a -> IO a
106
107         -- *** Applying @block@ to an exception handler
108
109         -- $block_handler
110
111         -- *** Interruptible operations
112
113         -- $interruptible
114
115         -- * Assertions
116
117         assert,         -- :: Bool -> a -> a
118
119         -- * Utilities
120
121         bracket,        -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO ()
122         bracket_,       -- :: IO a -> IO b -> IO c -> IO ()
123         bracketOnError,
124
125         finally,        -- :: IO a -> IO b -> IO a
126         
127 #ifdef __GLASGOW_HASKELL__
128         setUncaughtExceptionHandler,      -- :: (Exception -> IO ()) -> IO ()
129         getUncaughtExceptionHandler       -- :: IO (Exception -> IO ())
130 #endif
131   ) where
132
133 #ifdef __GLASGOW_HASKELL__
134 import GHC.Base
135 import GHC.Num
136 import GHC.Show
137 import GHC.IOBase ( IO )
138 import qualified GHC.IOBase as ExceptionBase
139 import qualified GHC.IOBase as New
140 import GHC.Conc hiding (setUncaughtExceptionHandler,
141                         getUncaughtExceptionHandler)
142 import Data.IORef       ( IORef, newIORef, readIORef, writeIORef )
143 import Foreign.C.String ( CString, withCString )
144 import GHC.Handle       ( stdout, hFlush )
145 #endif
146
147 #ifdef __HUGS__
148 import Prelude          hiding (catch)
149 import Hugs.Prelude     as New (ExitCode(..))
150 #endif
151
152 import qualified Control.Exception as New
153 import           Control.Exception ( throw, SomeException(..), block, unblock, evaluate, throwIO )
154 import System.IO.Error  hiding ( catch, try )
155 import System.IO.Unsafe (unsafePerformIO)
156 import Data.Dynamic
157 import Data.Either
158 import Data.Maybe
159
160 #ifdef __NHC__
161 import System.IO.Error (catch, ioError)
162 import IO              (bracket)
163 import DIOError         -- defn of IOError type
164
165 -- minimum needed for nhc98 to pretend it has Exceptions
166 type Exception   = IOError
167 type IOException = IOError
168 data ArithException
169 data ArrayException
170 data AsyncException
171
172 throwIO  :: Exception -> IO a
173 throwIO   = ioError
174 throw    :: Exception -> a
175 throw     = unsafePerformIO . throwIO
176
177 evaluate :: a -> IO a
178 evaluate x = x `seq` return x
179
180 ioErrors        :: Exception -> Maybe IOError
181 ioErrors e       = Just e
182 arithExceptions :: Exception -> Maybe ArithException
183 arithExceptions  = const Nothing
184 errorCalls      :: Exception -> Maybe String
185 errorCalls       = const Nothing
186 dynExceptions   :: Exception -> Maybe Dynamic
187 dynExceptions    = const Nothing
188 assertions      :: Exception -> Maybe String
189 assertions       = const Nothing
190 asyncExceptions :: Exception -> Maybe AsyncException
191 asyncExceptions  = const Nothing
192 userErrors      :: Exception -> Maybe String
193 userErrors (UserError _ s) = Just s
194 userErrors  _              = Nothing
195
196 block   :: IO a -> IO a
197 block    = id
198 unblock :: IO a -> IO a
199 unblock  = id
200
201 assert :: Bool -> a -> a
202 assert True  x = x
203 assert False _ = throw (UserError "" "Assertion failed")
204 #endif
205
206 -----------------------------------------------------------------------------
207 -- Catching exceptions
208
209 -- |This is the simplest of the exception-catching functions.  It
210 -- takes a single argument, runs it, and if an exception is raised
211 -- the \"handler\" is executed, with the value of the exception passed as an
212 -- argument.  Otherwise, the result is returned as normal.  For example:
213 --
214 -- >   catch (openFile f ReadMode) 
215 -- >       (\e -> hPutStr stderr ("Couldn't open "++f++": " ++ show e))
216 --
217 -- For catching exceptions in pure (non-'IO') expressions, see the
218 -- function 'evaluate'.
219 --
220 -- Note that due to Haskell\'s unspecified evaluation order, an
221 -- expression may return one of several possible exceptions: consider
222 -- the expression @error \"urk\" + 1 \`div\` 0@.  Does
223 -- 'catch' execute the handler passing
224 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
225 --
226 -- The answer is \"either\": 'catch' makes a
227 -- non-deterministic choice about which exception to catch.  If you
228 -- call it again, you might get a different exception back.  This is
229 -- ok, because 'catch' is an 'IO' computation.
230 --
231 -- Note that 'catch' catches all types of exceptions, and is generally
232 -- used for \"cleaning up\" before passing on the exception using
233 -- 'throwIO'.  It is not good practice to discard the exception and
234 -- continue, without first checking the type of the exception (it
235 -- might be a 'ThreadKilled', for example).  In this case it is usually better
236 -- to use 'catchJust' and select the kinds of exceptions to catch.
237 --
238 -- Also note that the "Prelude" also exports a function called
239 -- 'Prelude.catch' with a similar type to 'Control.OldException.catch',
240 -- except that the "Prelude" version only catches the IO and user
241 -- families of exceptions (as required by Haskell 98).  
242 --
243 -- We recommend either hiding the "Prelude" version of 'Prelude.catch'
244 -- when importing "Control.OldException": 
245 --
246 -- > import Prelude hiding (catch)
247 --
248 -- or importing "Control.OldException" qualified, to avoid name-clashes:
249 --
250 -- > import qualified Control.OldException as C
251 --
252 -- and then using @C.catch@
253 --
254
255 catch   :: IO a                 -- ^ The computation to run
256         -> (Exception -> IO a)  -- ^ Handler to invoke if an exception is raised
257         -> IO a
258 -- note: bundling the exceptions is done in the ExceptionBase.Exception
259 -- instance of Exception; see below.
260 catch = New.catch
261
262 -- | The function 'catchJust' is like 'catch', but it takes an extra
263 -- argument which is an /exception predicate/, a function which
264 -- selects which type of exceptions we\'re interested in.  There are
265 -- some predefined exception predicates for useful subsets of
266 -- exceptions: 'ioErrors', 'arithExceptions', and so on.  For example,
267 -- to catch just calls to the 'error' function, we could use
268 --
269 -- >   result <- catchJust errorCalls thing_to_try handler
270 --
271 -- Any other exceptions which are not matched by the predicate
272 -- are re-raised, and may be caught by an enclosing
273 -- 'catch' or 'catchJust'.
274 catchJust
275         :: (Exception -> Maybe b) -- ^ Predicate to select exceptions
276         -> IO a                   -- ^ Computation to run
277         -> (b -> IO a)            -- ^ Handler
278         -> IO a
279 catchJust p a handler = catch a handler'
280   where handler' e = case p e of 
281                         Nothing -> throw e
282                         Just b  -> handler b
283
284 -- | A version of 'catch' with the arguments swapped around; useful in
285 -- situations where the code for the handler is shorter.  For example:
286 --
287 -- >   do handle (\e -> exitWith (ExitFailure 1)) $
288 -- >      ...
289 handle     :: (Exception -> IO a) -> IO a -> IO a
290 handle     =  flip catch
291
292 -- | A version of 'catchJust' with the arguments swapped around (see
293 -- 'handle').
294 handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
295 handleJust p =  flip (catchJust p)
296
297 -----------------------------------------------------------------------------
298 -- 'mapException'
299
300 -- | This function maps one exception into another as proposed in the
301 -- paper \"A semantics for imprecise exceptions\".
302
303 -- Notice that the usage of 'unsafePerformIO' is safe here.
304
305 mapException :: (Exception -> Exception) -> a -> a
306 mapException f v = unsafePerformIO (catch (evaluate v)
307                                           (\x -> throw (f x)))
308
309 -----------------------------------------------------------------------------
310 -- 'try' and variations.
311
312 -- | Similar to 'catch', but returns an 'Either' result which is
313 -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an
314 -- exception was raised and its value is @e@.
315 --
316 -- >  try a = catch (Right `liftM` a) (return . Left)
317 --
318 -- Note: as with 'catch', it is only polite to use this variant if you intend
319 -- to re-throw the exception after performing whatever cleanup is needed.
320 -- Otherwise, 'tryJust' is generally considered to be better.
321 --
322 -- Also note that "System.IO.Error" also exports a function called
323 -- 'System.IO.Error.try' with a similar type to 'Control.OldException.try',
324 -- except that it catches only the IO and user families of exceptions
325 -- (as required by the Haskell 98 @IO@ module).
326
327 try :: IO a -> IO (Either Exception a)
328 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
329
330 -- | A variant of 'try' that takes an exception predicate to select
331 -- which exceptions are caught (c.f. 'catchJust').  If the exception
332 -- does not match the predicate, it is re-thrown.
333 tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a)
334 tryJust p a = do
335   r <- try a
336   case r of
337         Right v -> return (Right v)
338         Left  e -> case p e of
339                         Nothing -> throw e
340                         Just b  -> return (Left b)
341
342 -----------------------------------------------------------------------------
343 -- Dynamic exceptions
344
345 -- $dynamic
346 --  #DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an
347 -- interface for throwing and catching exceptions of type 'Dynamic'
348 -- (see "Data.Dynamic") which allows exception values of any type in
349 -- the 'Typeable' class to be thrown and caught.
350
351 -- | Raise any value as an exception, provided it is in the
352 -- 'Typeable' class.
353 throwDyn :: Typeable exception => exception -> b
354 #ifdef __NHC__
355 throwDyn exception = throw (UserError "" "dynamic exception")
356 #else
357 throwDyn exception = throw (DynException (toDyn exception))
358 #endif
359
360 #ifdef __GLASGOW_HASKELL__
361 -- | A variant of 'throwDyn' that throws the dynamic exception to an
362 -- arbitrary thread (GHC only: c.f. 'throwTo').
363 throwDynTo :: Typeable exception => ThreadId -> exception -> IO ()
364 throwDynTo t exception = New.throwTo t (DynException (toDyn exception))
365 #endif /* __GLASGOW_HASKELL__ */
366
367 -- | Catch dynamic exceptions of the required type.  All other
368 -- exceptions are re-thrown, including dynamic exceptions of the wrong
369 -- type.
370 --
371 -- When using dynamic exceptions it is advisable to define a new
372 -- datatype to use for your exception type, to avoid possible clashes
373 -- with dynamic exceptions used in other libraries.
374 --
375 catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a
376 #ifdef __NHC__
377 catchDyn m k = m        -- can't catch dyn exceptions in nhc98
378 #else
379 catchDyn m k = New.catch m handle
380   where handle ex = case ex of
381                            (DynException dyn) ->
382                                 case fromDynamic dyn of
383                                     Just exception  -> k exception
384                                     Nothing -> throw ex
385                            _ -> throw ex
386 #endif
387
388 -----------------------------------------------------------------------------
389 -- Exception Predicates
390
391 -- $preds
392 -- These pre-defined predicates may be used as the first argument to
393 -- 'catchJust', 'tryJust', or 'handleJust' to select certain common
394 -- classes of exceptions.
395 #ifndef __NHC__
396 ioErrors                :: Exception -> Maybe IOError
397 arithExceptions         :: Exception -> Maybe New.ArithException
398 errorCalls              :: Exception -> Maybe String
399 assertions              :: Exception -> Maybe String
400 dynExceptions           :: Exception -> Maybe Dynamic
401 asyncExceptions         :: Exception -> Maybe New.AsyncException
402 userErrors              :: Exception -> Maybe String
403
404 ioErrors (IOException e) = Just e
405 ioErrors _ = Nothing
406
407 arithExceptions (ArithException e) = Just e
408 arithExceptions _ = Nothing
409
410 errorCalls (ErrorCall e) = Just e
411 errorCalls _ = Nothing
412
413 assertions (AssertionFailed e) = Just e
414 assertions _ = Nothing
415
416 dynExceptions (DynException e) = Just e
417 dynExceptions _ = Nothing
418
419 asyncExceptions (AsyncException e) = Just e
420 asyncExceptions _ = Nothing
421
422 userErrors (IOException e) | isUserError e = Just (ioeGetErrorString e)
423 userErrors _ = Nothing
424 #endif
425 -----------------------------------------------------------------------------
426 -- Some Useful Functions
427
428 -- | When you want to acquire a resource, do some work with it, and
429 -- then release the resource, it is a good idea to use 'bracket',
430 -- because 'bracket' will install the necessary exception handler to
431 -- release the resource in the event that an exception is raised
432 -- during the computation.  If an exception is raised, then 'bracket' will 
433 -- re-raise the exception (after performing the release).
434 --
435 -- A common example is opening a file:
436 --
437 -- > bracket
438 -- >   (openFile "filename" ReadMode)
439 -- >   (hClose)
440 -- >   (\handle -> do { ... })
441 --
442 -- The arguments to 'bracket' are in this order so that we can partially apply 
443 -- it, e.g.:
444 --
445 -- > withFile name mode = bracket (openFile name mode) hClose
446 --
447 #ifndef __NHC__
448 bracket 
449         :: IO a         -- ^ computation to run first (\"acquire resource\")
450         -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
451         -> (a -> IO c)  -- ^ computation to run in-between
452         -> IO c         -- returns the value from the in-between computation
453 bracket before after thing =
454   block (do
455     a <- before 
456     r <- catch 
457            (unblock (thing a))
458            (\e -> do { after a; throw e })
459     after a
460     return r
461  )
462 #endif
463
464 -- | A specialised variant of 'bracket' with just a computation to run
465 -- afterward.
466 -- 
467 finally :: IO a         -- ^ computation to run first
468         -> IO b         -- ^ computation to run afterward (even if an exception 
469                         -- was raised)
470         -> IO a         -- returns the value from the first computation
471 a `finally` sequel =
472   block (do
473     r <- catch 
474              (unblock a)
475              (\e -> do { sequel; throw e })
476     sequel
477     return r
478   )
479
480 -- | A variant of 'bracket' where the return value from the first computation
481 -- is not required.
482 bracket_ :: IO a -> IO b -> IO c -> IO c
483 bracket_ before after thing = bracket before (const after) (const thing)
484
485 -- | Like bracket, but only performs the final action if there was an 
486 -- exception raised by the in-between computation.
487 bracketOnError
488         :: IO a         -- ^ computation to run first (\"acquire resource\")
489         -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
490         -> (a -> IO c)  -- ^ computation to run in-between
491         -> IO c         -- returns the value from the in-between computation
492 bracketOnError before after thing =
493   block (do
494     a <- before 
495     catch 
496         (unblock (thing a))
497         (\e -> do { after a; throw e })
498  )
499
500 -- -----------------------------------------------------------------------------
501 -- Asynchronous exceptions
502
503 {- $async
504
505  #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
506 external influences, and can be raised at any point during execution.
507 'StackOverflow' and 'HeapOverflow' are two examples of
508 system-generated asynchronous exceptions.
509
510 The primary source of asynchronous exceptions, however, is
511 'throwTo':
512
513 >  throwTo :: ThreadId -> Exception -> IO ()
514
515 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
516 running thread to raise an arbitrary exception in another thread.  The
517 exception is therefore asynchronous with respect to the target thread,
518 which could be doing anything at the time it receives the exception.
519 Great care should be taken with asynchronous exceptions; it is all too
520 easy to introduce race conditions by the over zealous use of
521 'throwTo'.
522 -}
523
524 {- $block_handler
525 There\'s an implied 'block' around every exception handler in a call
526 to one of the 'catch' family of functions.  This is because that is
527 what you want most of the time - it eliminates a common race condition
528 in starting an exception handler, because there may be no exception
529 handler on the stack to handle another exception if one arrives
530 immediately.  If asynchronous exceptions are blocked on entering the
531 handler, though, we have time to install a new exception handler
532 before being interrupted.  If this weren\'t the default, one would have
533 to write something like
534
535 >      block (
536 >           catch (unblock (...))
537 >                      (\e -> handler)
538 >      )
539
540 If you need to unblock asynchronous exceptions again in the exception
541 handler, just use 'unblock' as normal.
542
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
546 'block'.
547 -}
548
549 {- $interruptible
550
551 Some operations are /interruptible/, which means that they can receive
552 asynchronous exceptions even in the scope of a 'block'.  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
559
560 >      block (
561 >         a <- takeMVar m
562 >         catch (unblock (...))
563 >               (\e -> ...)
564 >      )
565
566 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
567 then this particular
568 combination could lead to deadlock, because the thread itself would be
569 blocked in a state where it can\'t receive any asynchronous exceptions.
570 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
571 safe in the knowledge that the thread can receive exceptions right up
572 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
573 Similar arguments apply for other interruptible operations like
574 'System.IO.openFile'.
575 -}
576
577 #if !(__GLASGOW_HASKELL__ || __NHC__)
578 assert :: Bool -> a -> a
579 assert True x = x
580 assert False _ = throw (AssertionFailed "")
581 #endif
582
583
584 #ifdef __GLASGOW_HASKELL__
585 {-# NOINLINE uncaughtExceptionHandler #-}
586 uncaughtExceptionHandler :: IORef (Exception -> IO ())
587 uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler)
588    where
589       defaultHandler :: Exception -> IO ()
590       defaultHandler ex = do
591          (hFlush stdout) `New.catchAny` (\ _ -> return ())
592          let msg = case ex of
593                Deadlock    -> "no threads to run:  infinite loop or deadlock?"
594                ErrorCall s -> s
595                other       -> showsPrec 0 other ""
596          withCString "%s" $ \cfmt ->
597           withCString msg $ \cmsg ->
598             errorBelch cfmt cmsg
599
600 -- don't use errorBelch() directly, because we cannot call varargs functions
601 -- using the FFI.
602 foreign import ccall unsafe "HsBase.h errorBelch2"
603    errorBelch :: CString -> CString -> IO ()
604
605 setUncaughtExceptionHandler :: (Exception -> IO ()) -> IO ()
606 setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler
607
608 getUncaughtExceptionHandler :: IO (Exception -> IO ())
609 getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler
610 #endif
611
612 -- ------------------------------------------------------------------------
613 -- Exception datatype and operations
614
615 -- |The type of exceptions.  Every kind of system-generated exception
616 -- has a constructor in the 'Exception' type, and values of other
617 -- types may be injected into 'Exception' by coercing them to
618 -- 'Data.Dynamic.Dynamic' (see the section on Dynamic Exceptions:
619 -- "Control.OldException\#DynamicExceptions").
620 data Exception
621   = ArithException      New.ArithException
622         -- ^Exceptions raised by arithmetic
623         -- operations.  (NOTE: GHC currently does not throw
624         -- 'ArithException's except for 'DivideByZero').
625   | ArrayException      New.ArrayException
626         -- ^Exceptions raised by array-related
627         -- operations.  (NOTE: GHC currently does not throw
628         -- 'ArrayException's).
629   | AssertionFailed     String
630         -- ^This exception is thrown by the
631         -- 'assert' operation when the condition
632         -- fails.  The 'String' argument contains the
633         -- location of the assertion in the source program.
634   | AsyncException      New.AsyncException
635         -- ^Asynchronous exceptions (see section on Asynchronous Exceptions: "Control.OldException\#AsynchronousExceptions").
636   | BlockedOnDeadMVar
637         -- ^The current thread was executing a call to
638         -- 'Control.Concurrent.MVar.takeMVar' that could never return,
639         -- because there are no other references to this 'MVar'.
640   | BlockedIndefinitely
641         -- ^The current thread was waiting to retry an atomic memory transaction
642         -- that could never become possible to complete because there are no other
643         -- threads referring to any of the TVars involved.
644   | NestedAtomically
645         -- ^The runtime detected an attempt to nest one STM transaction
646         -- inside another one, presumably due to the use of 
647         -- 'unsafePeformIO' with 'atomically'.
648   | Deadlock
649         -- ^There are no runnable threads, so the program is
650         -- deadlocked.  The 'Deadlock' exception is
651         -- raised in the main thread only (see also: "Control.Concurrent").
652   | DynException        Dynamic
653         -- ^Dynamically typed exceptions (see section on Dynamic Exceptions: "Control.OldException\#DynamicExceptions").
654   | ErrorCall           String
655         -- ^The 'ErrorCall' exception is thrown by 'error'.  The 'String'
656         -- argument of 'ErrorCall' is the string passed to 'error' when it was
657         -- called.
658   | ExitException       New.ExitCode
659         -- ^The 'ExitException' exception is thrown by 'System.Exit.exitWith' (and
660         -- 'System.Exit.exitFailure').  The 'ExitCode' argument is the value passed 
661         -- to 'System.Exit.exitWith'.  An unhandled 'ExitException' exception in the
662         -- main thread will cause the program to be terminated with the given 
663         -- exit code.
664   | IOException         New.IOException
665         -- ^These are the standard IO exceptions generated by
666         -- Haskell\'s @IO@ operations.  See also "System.IO.Error".
667   | NoMethodError       String
668         -- ^An attempt was made to invoke a class method which has
669         -- no definition in this instance, and there was no default
670         -- definition given in the class declaration.  GHC issues a
671         -- warning when you compile an instance which has missing
672         -- methods.
673   | NonTermination
674         -- ^The current thread is stuck in an infinite loop.  This
675         -- exception may or may not be thrown when the program is
676         -- non-terminating.
677   | PatternMatchFail    String
678         -- ^A pattern matching failure.  The 'String' argument should contain a
679         -- descriptive message including the function name, source file
680         -- and line number.
681   | RecConError         String
682         -- ^An attempt was made to evaluate a field of a record
683         -- for which no value was given at construction time.  The
684         -- 'String' argument gives the location of the
685         -- record construction in the source program.
686   | RecSelError         String
687         -- ^A field selection was attempted on a constructor that
688         -- doesn\'t have the requested field.  This can happen with
689         -- multi-constructor records when one or more fields are
690         -- missing from some of the constructors.  The
691         -- 'String' argument gives the location of the
692         -- record selection in the source program.
693   | RecUpdError         String
694         -- ^An attempt was made to update a field in a record,
695         -- where the record doesn\'t have the requested field.  This can
696         -- only occur with multi-constructor records, when one or more
697         -- fields are missing from some of the constructors.  The
698         -- 'String' argument gives the location of the
699         -- record update in the source program.
700 INSTANCE_TYPEABLE0(Exception,exceptionTc,"Exception")
701
702 nonTermination :: SomeException
703 nonTermination = New.toException NonTermination
704
705 -- helper type for simplifying the type casting logic below
706 data Caster = forall e . ExceptionBase.Exception e => Caster (e -> Exception)
707
708 instance New.Exception Exception where
709   -- We need to collect all the sorts of exceptions that used to be
710   -- bundled up into the Exception type, and rebundle them for
711   -- legacy handlers.
712   fromException (SomeException exc) = foldr tryCast Nothing casters where
713     tryCast (Caster f) e = case cast exc of
714       Just exc -> Just (f exc)
715       _        -> e
716     casters =
717       [Caster (\e -> e),
718        Caster (\exc -> ArithException exc),
719        Caster (\exc -> ArrayException exc),
720        Caster (\(New.AssertionFailed err) -> AssertionFailed err),
721        Caster (\exc -> AsyncException exc),
722        Caster (\New.BlockedOnDeadMVar -> BlockedOnDeadMVar),
723        Caster (\New.BlockedIndefinitely -> BlockedIndefinitely),
724        Caster (\New.NestedAtomically -> NestedAtomically),
725        Caster (\New.Deadlock -> Deadlock),
726        Caster (\exc -> DynException exc),
727        Caster (\(New.ErrorCall err) -> ErrorCall err),
728        Caster (\exc -> ExitException exc),
729        Caster (\exc -> IOException exc),
730        Caster (\(New.NoMethodError err) -> NoMethodError err),
731        Caster (\New.NonTermination -> NonTermination),
732        Caster (\(New.PatternMatchFail err) -> PatternMatchFail err),
733        Caster (\(New.RecConError err) -> RecConError err),
734        Caster (\(New.RecSelError err) -> RecSelError err),
735        Caster (\(New.RecUpdError err) -> RecUpdError err)]
736
737   -- Unbundle exceptions.
738   toException (ArithException exc)   = SomeException exc
739   toException (ArrayException exc)   = SomeException exc
740   toException (AssertionFailed err)  = SomeException (New.AssertionFailed err)
741   toException (AsyncException exc)   = SomeException exc
742   toException BlockedOnDeadMVar      = SomeException New.BlockedOnDeadMVar
743   toException BlockedIndefinitely    = SomeException New.BlockedIndefinitely
744   toException NestedAtomically       = SomeException New.NestedAtomically
745   toException Deadlock               = SomeException New.Deadlock
746   toException (DynException exc)     = SomeException exc
747   toException (ErrorCall err)        = SomeException (New.ErrorCall err)
748   toException (ExitException exc)    = SomeException exc
749   toException (IOException exc)      = SomeException exc
750   toException (NoMethodError err)    = SomeException (New.NoMethodError err)
751   toException NonTermination         = SomeException New.NonTermination
752   toException (PatternMatchFail err) = SomeException (New.PatternMatchFail err)
753   toException (RecConError err)      = SomeException (New.RecConError err)
754   toException (RecSelError err)      = SomeException (New.RecSelError err)
755   toException (RecUpdError err)      = SomeException (New.RecUpdError err)
756
757 instance Show Exception where
758   showsPrec _ (IOException err)          = shows err
759   showsPrec _ (ArithException err)       = shows err
760   showsPrec _ (ArrayException err)       = shows err
761   showsPrec _ (ErrorCall err)            = showString err
762   showsPrec _ (ExitException err)        = showString "exit: " . shows err
763   showsPrec _ (NoMethodError err)        = showString err
764   showsPrec _ (PatternMatchFail err)     = showString err
765   showsPrec _ (RecSelError err)          = showString err
766   showsPrec _ (RecConError err)          = showString err
767   showsPrec _ (RecUpdError err)          = showString err
768   showsPrec _ (AssertionFailed err)      = showString err
769   showsPrec _ (DynException err)         = showString "exception :: " . showsTypeRep (dynTypeRep err)
770   showsPrec _ (AsyncException e)         = shows e
771   showsPrec p BlockedOnDeadMVar          = showsPrec p New.BlockedOnDeadMVar
772   showsPrec p BlockedIndefinitely        = showsPrec p New.BlockedIndefinitely
773   showsPrec p NestedAtomically           = showsPrec p New.NestedAtomically
774   showsPrec p NonTermination             = showsPrec p New.NonTermination
775   showsPrec p Deadlock                   = showsPrec p New.Deadlock
776
777 instance Eq Exception where
778   IOException e1      == IOException e2      = e1 == e2
779   ArithException e1   == ArithException e2   = e1 == e2
780   ArrayException e1   == ArrayException e2   = e1 == e2
781   ErrorCall e1        == ErrorCall e2        = e1 == e2
782   ExitException e1    == ExitException e2    = e1 == e2
783   NoMethodError e1    == NoMethodError e2    = e1 == e2
784   PatternMatchFail e1 == PatternMatchFail e2 = e1 == e2
785   RecSelError e1      == RecSelError e2      = e1 == e2
786   RecConError e1      == RecConError e2      = e1 == e2
787   RecUpdError e1      == RecUpdError e2      = e1 == e2
788   AssertionFailed e1  == AssertionFailed e2  = e1 == e2
789   DynException _      == DynException _      = False -- incomparable
790   AsyncException e1   == AsyncException e2   = e1 == e2
791   BlockedOnDeadMVar   == BlockedOnDeadMVar   = True
792   NonTermination      == NonTermination      = True
793   NestedAtomically    == NestedAtomically    = True
794   Deadlock            == Deadlock            = True
795   _                   == _                   = False
796