00b1cf47e9605b3edb4532fd585754858e166497
[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 GHC.IOBase (catchException)
139 import qualified GHC.IOBase as ExceptionBase
140 import qualified GHC.IOBase 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.Handle       ( stdout, 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 ( throw, SomeException, 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 catch io handler =
260     -- We need to catch all the sorts of exceptions that used to be
261     -- bundled up into the Exception type, and rebundle them for the
262     -- legacy handler we've been given.
263     io `New.catches`
264         [New.Handler (\e -> handler e),
265          New.Handler (\exc -> handler (ArithException exc)),
266          New.Handler (\exc -> handler (ArrayException exc)),
267          New.Handler (\(New.AssertionFailed err) -> handler (AssertionFailed err)),
268          New.Handler (\exc -> handler (AsyncException exc)),
269          New.Handler (\New.BlockedOnDeadMVar -> handler BlockedOnDeadMVar),
270          New.Handler (\New.BlockedIndefinitely -> handler BlockedIndefinitely),
271          New.Handler (\New.NestedAtomically -> handler NestedAtomically),
272          New.Handler (\New.Deadlock -> handler Deadlock),
273          New.Handler (\exc -> handler (DynException exc)),
274          New.Handler (\(New.ErrorCall err) -> handler (ErrorCall err)),
275          New.Handler (\exc -> handler (ExitException exc)),
276          New.Handler (\exc -> handler (IOException exc)),
277          New.Handler (\(New.NoMethodError err) -> handler (NoMethodError err)),
278          New.Handler (\New.NonTermination -> handler NonTermination),
279          New.Handler (\(New.PatternMatchFail err) -> handler (PatternMatchFail err)),
280          New.Handler (\(New.RecConError err) -> handler (RecConError err)),
281          New.Handler (\(New.RecSelError err) -> handler (RecSelError err)),
282          New.Handler (\(New.RecUpdError err) -> handler (RecUpdError err))]
283
284 -- | The function 'catchJust' is like 'catch', but it takes an extra
285 -- argument which is an /exception predicate/, a function which
286 -- selects which type of exceptions we\'re interested in.  There are
287 -- some predefined exception predicates for useful subsets of
288 -- exceptions: 'ioErrors', 'arithExceptions', and so on.  For example,
289 -- to catch just calls to the 'error' function, we could use
290 --
291 -- >   result <- catchJust errorCalls thing_to_try handler
292 --
293 -- Any other exceptions which are not matched by the predicate
294 -- are re-raised, and may be caught by an enclosing
295 -- 'catch' or 'catchJust'.
296 catchJust
297         :: (Exception -> Maybe b) -- ^ Predicate to select exceptions
298         -> IO a                   -- ^ Computation to run
299         -> (b -> IO a)            -- ^ Handler
300         -> IO a
301 catchJust p a handler = catch a handler'
302   where handler' e = case p e of 
303                         Nothing -> throw e
304                         Just b  -> handler b
305
306 -- | A version of 'catch' with the arguments swapped around; useful in
307 -- situations where the code for the handler is shorter.  For example:
308 --
309 -- >   do handle (\e -> exitWith (ExitFailure 1)) $
310 -- >      ...
311 handle     :: (Exception -> IO a) -> IO a -> IO a
312 handle     =  flip catch
313
314 -- | A version of 'catchJust' with the arguments swapped around (see
315 -- 'handle').
316 handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
317 handleJust p =  flip (catchJust p)
318
319 -----------------------------------------------------------------------------
320 -- 'mapException'
321
322 -- | This function maps one exception into another as proposed in the
323 -- paper \"A semantics for imprecise exceptions\".
324
325 -- Notice that the usage of 'unsafePerformIO' is safe here.
326
327 mapException :: (Exception -> Exception) -> a -> a
328 mapException f v = unsafePerformIO (catch (evaluate v)
329                                           (\x -> throw (f x)))
330
331 -----------------------------------------------------------------------------
332 -- 'try' and variations.
333
334 -- | Similar to 'catch', but returns an 'Either' result which is
335 -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an
336 -- exception was raised and its value is @e@.
337 --
338 -- >  try a = catch (Right `liftM` a) (return . Left)
339 --
340 -- Note: as with 'catch', it is only polite to use this variant if you intend
341 -- to re-throw the exception after performing whatever cleanup is needed.
342 -- Otherwise, 'tryJust' is generally considered to be better.
343 --
344 -- Also note that "System.IO.Error" also exports a function called
345 -- 'System.IO.Error.try' with a similar type to 'Control.OldException.try',
346 -- except that it catches only the IO and user families of exceptions
347 -- (as required by the Haskell 98 @IO@ module).
348
349 try :: IO a -> IO (Either Exception a)
350 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
351
352 -- | A variant of 'try' that takes an exception predicate to select
353 -- which exceptions are caught (c.f. 'catchJust').  If the exception
354 -- does not match the predicate, it is re-thrown.
355 tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a)
356 tryJust p a = do
357   r <- try a
358   case r of
359         Right v -> return (Right v)
360         Left  e -> case p e of
361                         Nothing -> throw e
362                         Just b  -> return (Left b)
363
364 -----------------------------------------------------------------------------
365 -- Dynamic exceptions
366
367 -- $dynamic
368 --  #DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an
369 -- interface for throwing and catching exceptions of type 'Dynamic'
370 -- (see "Data.Dynamic") which allows exception values of any type in
371 -- the 'Typeable' class to be thrown and caught.
372
373 -- | Raise any value as an exception, provided it is in the
374 -- 'Typeable' class.
375 throwDyn :: Typeable exception => exception -> b
376 #ifdef __NHC__
377 throwDyn exception = throw (UserError "" "dynamic exception")
378 #else
379 throwDyn exception = throw (DynException (toDyn exception))
380 #endif
381
382 #ifdef __GLASGOW_HASKELL__
383 -- | A variant of 'throwDyn' that throws the dynamic exception to an
384 -- arbitrary thread (GHC only: c.f. 'throwTo').
385 throwDynTo :: Typeable exception => ThreadId -> exception -> IO ()
386 throwDynTo t exception = New.throwTo t (DynException (toDyn exception))
387 #endif /* __GLASGOW_HASKELL__ */
388
389 -- | Catch dynamic exceptions of the required type.  All other
390 -- exceptions are re-thrown, including dynamic exceptions of the wrong
391 -- type.
392 --
393 -- When using dynamic exceptions it is advisable to define a new
394 -- datatype to use for your exception type, to avoid possible clashes
395 -- with dynamic exceptions used in other libraries.
396 --
397 catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a
398 #ifdef __NHC__
399 catchDyn m k = m        -- can't catch dyn exceptions in nhc98
400 #else
401 catchDyn m k = catchException m handle
402   where handle ex = case ex of
403                            (DynException dyn) ->
404                                 case fromDynamic dyn of
405                                     Just exception  -> k exception
406                                     Nothing -> throw ex
407                            _ -> throw ex
408 #endif
409
410 -----------------------------------------------------------------------------
411 -- Exception Predicates
412
413 -- $preds
414 -- These pre-defined predicates may be used as the first argument to
415 -- 'catchJust', 'tryJust', or 'handleJust' to select certain common
416 -- classes of exceptions.
417 #ifndef __NHC__
418 ioErrors                :: Exception -> Maybe IOError
419 arithExceptions         :: Exception -> Maybe New.ArithException
420 errorCalls              :: Exception -> Maybe String
421 assertions              :: Exception -> Maybe String
422 dynExceptions           :: Exception -> Maybe Dynamic
423 asyncExceptions         :: Exception -> Maybe New.AsyncException
424 userErrors              :: Exception -> Maybe String
425
426 ioErrors (IOException e) = Just e
427 ioErrors _ = Nothing
428
429 arithExceptions (ArithException e) = Just e
430 arithExceptions _ = Nothing
431
432 errorCalls (ErrorCall e) = Just e
433 errorCalls _ = Nothing
434
435 assertions (AssertionFailed e) = Just e
436 assertions _ = Nothing
437
438 dynExceptions (DynException e) = Just e
439 dynExceptions _ = Nothing
440
441 asyncExceptions (AsyncException e) = Just e
442 asyncExceptions _ = Nothing
443
444 userErrors (IOException e) | isUserError e = Just (ioeGetErrorString e)
445 userErrors _ = Nothing
446 #endif
447 -----------------------------------------------------------------------------
448 -- Some Useful Functions
449
450 -- | When you want to acquire a resource, do some work with it, and
451 -- then release the resource, it is a good idea to use 'bracket',
452 -- because 'bracket' will install the necessary exception handler to
453 -- release the resource in the event that an exception is raised
454 -- during the computation.  If an exception is raised, then 'bracket' will 
455 -- re-raise the exception (after performing the release).
456 --
457 -- A common example is opening a file:
458 --
459 -- > bracket
460 -- >   (openFile "filename" ReadMode)
461 -- >   (hClose)
462 -- >   (\handle -> do { ... })
463 --
464 -- The arguments to 'bracket' are in this order so that we can partially apply 
465 -- it, e.g.:
466 --
467 -- > withFile name mode = bracket (openFile name mode) hClose
468 --
469 #ifndef __NHC__
470 bracket 
471         :: IO a         -- ^ computation to run first (\"acquire resource\")
472         -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
473         -> (a -> IO c)  -- ^ computation to run in-between
474         -> IO c         -- returns the value from the in-between computation
475 bracket before after thing =
476   block (do
477     a <- before 
478     r <- catch 
479            (unblock (thing a))
480            (\e -> do { after a; throw e })
481     after a
482     return r
483  )
484 #endif
485
486 -- | A specialised variant of 'bracket' with just a computation to run
487 -- afterward.
488 -- 
489 finally :: IO a         -- ^ computation to run first
490         -> IO b         -- ^ computation to run afterward (even if an exception 
491                         -- was raised)
492         -> IO a         -- returns the value from the first computation
493 a `finally` sequel =
494   block (do
495     r <- catch 
496              (unblock a)
497              (\e -> do { sequel; throw e })
498     sequel
499     return r
500   )
501
502 -- | A variant of 'bracket' where the return value from the first computation
503 -- is not required.
504 bracket_ :: IO a -> IO b -> IO c -> IO c
505 bracket_ before after thing = bracket before (const after) (const thing)
506
507 -- | Like bracket, but only performs the final action if there was an 
508 -- exception raised by the in-between computation.
509 bracketOnError
510         :: IO a         -- ^ computation to run first (\"acquire resource\")
511         -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
512         -> (a -> IO c)  -- ^ computation to run in-between
513         -> IO c         -- returns the value from the in-between computation
514 bracketOnError before after thing =
515   block (do
516     a <- before 
517     catch 
518         (unblock (thing a))
519         (\e -> do { after a; throw e })
520  )
521
522 -- -----------------------------------------------------------------------------
523 -- Asynchronous exceptions
524
525 {- $async
526
527  #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
528 external influences, and can be raised at any point during execution.
529 'StackOverflow' and 'HeapOverflow' are two examples of
530 system-generated asynchronous exceptions.
531
532 The primary source of asynchronous exceptions, however, is
533 'throwTo':
534
535 >  throwTo :: ThreadId -> Exception -> IO ()
536
537 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
538 running thread to raise an arbitrary exception in another thread.  The
539 exception is therefore asynchronous with respect to the target thread,
540 which could be doing anything at the time it receives the exception.
541 Great care should be taken with asynchronous exceptions; it is all too
542 easy to introduce race conditions by the over zealous use of
543 'throwTo'.
544 -}
545
546 {- $block_handler
547 There\'s an implied 'block' around every exception handler in a call
548 to one of the 'catch' family of functions.  This is because that is
549 what you want most of the time - it eliminates a common race condition
550 in starting an exception handler, because there may be no exception
551 handler on the stack to handle another exception if one arrives
552 immediately.  If asynchronous exceptions are blocked on entering the
553 handler, though, we have time to install a new exception handler
554 before being interrupted.  If this weren\'t the default, one would have
555 to write something like
556
557 >      block (
558 >           catch (unblock (...))
559 >                      (\e -> handler)
560 >      )
561
562 If you need to unblock asynchronous exceptions again in the exception
563 handler, just use 'unblock' as normal.
564
565 Note that 'try' and friends /do not/ have a similar default, because
566 there is no exception handler in this case.  If you want to use 'try'
567 in an asynchronous-exception-safe way, you will need to use
568 'block'.
569 -}
570
571 {- $interruptible
572
573 Some operations are /interruptible/, which means that they can receive
574 asynchronous exceptions even in the scope of a 'block'.  Any function
575 which may itself block is defined as interruptible; this includes
576 'Control.Concurrent.MVar.takeMVar'
577 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
578 and most operations which perform
579 some I\/O with the outside world.  The reason for having
580 interruptible operations is so that we can write things like
581
582 >      block (
583 >         a <- takeMVar m
584 >         catch (unblock (...))
585 >               (\e -> ...)
586 >      )
587
588 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
589 then this particular
590 combination could lead to deadlock, because the thread itself would be
591 blocked in a state where it can\'t receive any asynchronous exceptions.
592 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
593 safe in the knowledge that the thread can receive exceptions right up
594 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
595 Similar arguments apply for other interruptible operations like
596 'System.IO.openFile'.
597 -}
598
599 #if !(__GLASGOW_HASKELL__ || __NHC__)
600 assert :: Bool -> a -> a
601 assert True x = x
602 assert False _ = throw (AssertionFailed "")
603 #endif
604
605
606 #ifdef __GLASGOW_HASKELL__
607 {-# NOINLINE uncaughtExceptionHandler #-}
608 uncaughtExceptionHandler :: IORef (Exception -> IO ())
609 uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler)
610    where
611       defaultHandler :: Exception -> IO ()
612       defaultHandler ex = do
613          (hFlush stdout) `New.catchAny` (\ _ -> return ())
614          let msg = case ex of
615                Deadlock    -> "no threads to run:  infinite loop or deadlock?"
616                ErrorCall s -> s
617                other       -> showsPrec 0 other ""
618          withCString "%s" $ \cfmt ->
619           withCString msg $ \cmsg ->
620             errorBelch cfmt cmsg
621
622 -- don't use errorBelch() directly, because we cannot call varargs functions
623 -- using the FFI.
624 foreign import ccall unsafe "HsBase.h errorBelch2"
625    errorBelch :: CString -> CString -> IO ()
626
627 setUncaughtExceptionHandler :: (Exception -> IO ()) -> IO ()
628 setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler
629
630 getUncaughtExceptionHandler :: IO (Exception -> IO ())
631 getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler
632 #endif
633
634 -- ------------------------------------------------------------------------
635 -- Exception datatype and operations
636
637 -- |The type of exceptions.  Every kind of system-generated exception
638 -- has a constructor in the 'Exception' type, and values of other
639 -- types may be injected into 'Exception' by coercing them to
640 -- 'Data.Dynamic.Dynamic' (see the section on Dynamic Exceptions:
641 -- "Control.OldException\#DynamicExceptions").
642 data Exception
643   = ArithException      New.ArithException
644         -- ^Exceptions raised by arithmetic
645         -- operations.  (NOTE: GHC currently does not throw
646         -- 'ArithException's except for 'DivideByZero').
647   | ArrayException      New.ArrayException
648         -- ^Exceptions raised by array-related
649         -- operations.  (NOTE: GHC currently does not throw
650         -- 'ArrayException's).
651   | AssertionFailed     String
652         -- ^This exception is thrown by the
653         -- 'assert' operation when the condition
654         -- fails.  The 'String' argument contains the
655         -- location of the assertion in the source program.
656   | AsyncException      New.AsyncException
657         -- ^Asynchronous exceptions (see section on Asynchronous Exceptions: "Control.OldException\#AsynchronousExceptions").
658   | BlockedOnDeadMVar
659         -- ^The current thread was executing a call to
660         -- 'Control.Concurrent.MVar.takeMVar' that could never return,
661         -- because there are no other references to this 'MVar'.
662   | BlockedIndefinitely
663         -- ^The current thread was waiting to retry an atomic memory transaction
664         -- that could never become possible to complete because there are no other
665         -- threads referring to any of the TVars involved.
666   | NestedAtomically
667         -- ^The runtime detected an attempt to nest one STM transaction
668         -- inside another one, presumably due to the use of 
669         -- 'unsafePeformIO' with 'atomically'.
670   | Deadlock
671         -- ^There are no runnable threads, so the program is
672         -- deadlocked.  The 'Deadlock' exception is
673         -- raised in the main thread only (see also: "Control.Concurrent").
674   | DynException        Dynamic
675         -- ^Dynamically typed exceptions (see section on Dynamic Exceptions: "Control.OldException\#DynamicExceptions").
676   | ErrorCall           String
677         -- ^The 'ErrorCall' exception is thrown by 'error'.  The 'String'
678         -- argument of 'ErrorCall' is the string passed to 'error' when it was
679         -- called.
680   | ExitException       New.ExitCode
681         -- ^The 'ExitException' exception is thrown by 'System.Exit.exitWith' (and
682         -- 'System.Exit.exitFailure').  The 'ExitCode' argument is the value passed 
683         -- to 'System.Exit.exitWith'.  An unhandled 'ExitException' exception in the
684         -- main thread will cause the program to be terminated with the given 
685         -- exit code.
686   | IOException         New.IOException
687         -- ^These are the standard IO exceptions generated by
688         -- Haskell\'s @IO@ operations.  See also "System.IO.Error".
689   | NoMethodError       String
690         -- ^An attempt was made to invoke a class method which has
691         -- no definition in this instance, and there was no default
692         -- definition given in the class declaration.  GHC issues a
693         -- warning when you compile an instance which has missing
694         -- methods.
695   | NonTermination
696         -- ^The current thread is stuck in an infinite loop.  This
697         -- exception may or may not be thrown when the program is
698         -- non-terminating.
699   | PatternMatchFail    String
700         -- ^A pattern matching failure.  The 'String' argument should contain a
701         -- descriptive message including the function name, source file
702         -- and line number.
703   | RecConError         String
704         -- ^An attempt was made to evaluate a field of a record
705         -- for which no value was given at construction time.  The
706         -- 'String' argument gives the location of the
707         -- record construction in the source program.
708   | RecSelError         String
709         -- ^A field selection was attempted on a constructor that
710         -- doesn\'t have the requested field.  This can happen with
711         -- multi-constructor records when one or more fields are
712         -- missing from some of the constructors.  The
713         -- 'String' argument gives the location of the
714         -- record selection in the source program.
715   | RecUpdError         String
716         -- ^An attempt was made to update a field in a record,
717         -- where the record doesn\'t have the requested field.  This can
718         -- only occur with multi-constructor records, when one or more
719         -- fields are missing from some of the constructors.  The
720         -- 'String' argument gives the location of the
721         -- record update in the source program.
722 INSTANCE_TYPEABLE0(Exception,exceptionTc,"Exception")
723
724 nonTermination :: SomeException
725 nonTermination = New.toException NonTermination
726
727 -- For now at least, make the monolithic Exception type an instance of
728 -- the Exception class
729 instance New.Exception Exception
730
731 instance Show Exception where
732   showsPrec _ (IOException err)          = shows err
733   showsPrec _ (ArithException err)       = shows err
734   showsPrec _ (ArrayException err)       = shows err
735   showsPrec _ (ErrorCall err)            = showString err
736   showsPrec _ (ExitException err)        = showString "exit: " . shows err
737   showsPrec _ (NoMethodError err)        = showString err
738   showsPrec _ (PatternMatchFail err)     = showString err
739   showsPrec _ (RecSelError err)          = showString err
740   showsPrec _ (RecConError err)          = showString err
741   showsPrec _ (RecUpdError err)          = showString err
742   showsPrec _ (AssertionFailed err)      = showString err
743   showsPrec _ (DynException err)         = showString "exception :: " . showsTypeRep (dynTypeRep err)
744   showsPrec _ (AsyncException e)         = shows e
745   showsPrec p BlockedOnDeadMVar          = showsPrec p New.BlockedOnDeadMVar
746   showsPrec p BlockedIndefinitely        = showsPrec p New.BlockedIndefinitely
747   showsPrec p NestedAtomically           = showsPrec p New.NestedAtomically
748   showsPrec p NonTermination             = showsPrec p New.NonTermination
749   showsPrec p Deadlock                   = showsPrec p New.Deadlock
750
751 instance Eq Exception where
752   IOException e1      == IOException e2      = e1 == e2
753   ArithException e1   == ArithException e2   = e1 == e2
754   ArrayException e1   == ArrayException e2   = e1 == e2
755   ErrorCall e1        == ErrorCall e2        = e1 == e2
756   ExitException e1    == ExitException e2    = e1 == e2
757   NoMethodError e1    == NoMethodError e2    = e1 == e2
758   PatternMatchFail e1 == PatternMatchFail e2 = e1 == e2
759   RecSelError e1      == RecSelError e2      = e1 == e2
760   RecConError e1      == RecConError e2      = e1 == e2
761   RecUpdError e1      == RecUpdError e2      = e1 == e2
762   AssertionFailed e1  == AssertionFailed e2  = e1 == e2
763   DynException _      == DynException _      = False -- incomparable
764   AsyncException e1   == AsyncException e2   = e1 == e2
765   BlockedOnDeadMVar   == BlockedOnDeadMVar   = True
766   NonTermination      == NonTermination      = True
767   NestedAtomically    == NestedAtomically    = True
768   Deadlock            == Deadlock            = True
769   _                   == _                   = False
770