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