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