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