Extend nhc98's Exception type to resemble ghc's more closely
[ghc-base.git] / Control / Exception.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Control.Exception
4 -- Copyright   :  (c) The University of Glasgow 2001
5 -- License     :  BSD-style (see the file libraries/base/LICENSE)
6 -- 
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  experimental
9 -- Portability :  non-portable (extended exceptions)
10 --
11 -- This module provides support for raising and catching both built-in
12 -- and user-defined exceptions.
13 --
14 -- In addition to exceptions thrown by 'IO' operations, exceptions may
15 -- be thrown by pure code (imprecise exceptions) or by external events
16 -- (asynchronous exceptions), but may only be caught in the 'IO' monad.
17 -- For more details, see:
18 --
19 --  * /A semantics for imprecise exceptions/, by Simon Peyton Jones,
20 --    Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson,
21 --    in /PLDI'99/.
22 --
23 --  * /Asynchronous exceptions in Haskell/, by Simon Marlow, Simon Peyton
24 --    Jones, Andy Moran and John Reppy, in /PLDI'01/.
25 --
26 -----------------------------------------------------------------------------
27
28 module Control.Exception (
29
30         -- * The Exception type
31         Exception(..),          -- instance Eq, Ord, Show, Typeable
32         IOException,            -- instance Eq, Ord, Show, Typeable
33         ArithException(..),     -- instance Eq, Ord, Show, Typeable
34         ArrayException(..),     -- instance Eq, Ord, Show, Typeable
35         AsyncException(..),     -- instance Eq, Ord, Show, Typeable
36
37         -- * Throwing exceptions
38         throwIO,        -- :: Exception -> IO a
39         throw,          -- :: Exception -> a
40         ioError,        -- :: IOError -> IO a
41 #ifdef __GLASGOW_HASKELL__
42         throwTo,        -- :: ThreadId -> Exception -> a
43 #endif
44
45         -- * Catching Exceptions
46
47         -- |There are several functions for catching and examining
48         -- exceptions; all of them may only be used from within the
49         -- 'IO' monad.
50
51         -- ** The @catch@ functions
52         catch,     -- :: IO a -> (Exception -> IO a) -> IO a
53         catchJust, -- :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a
54
55         -- ** The @handle@ functions
56         handle,    -- :: (Exception -> IO a) -> IO a -> IO a
57         handleJust,-- :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
58
59         -- ** The @try@ functions
60         try,       -- :: IO a -> IO (Either Exception a)
61         tryJust,   -- :: (Exception -> Maybe b) -> a    -> IO (Either b a)
62
63         -- ** The @evaluate@ function
64         evaluate,  -- :: a -> IO a
65
66         -- ** The @mapException@ function
67         mapException,           -- :: (Exception -> Exception) -> a -> a
68
69         -- ** Exception predicates
70         
71         -- $preds
72
73         ioErrors,               -- :: Exception -> Maybe IOError
74         arithExceptions,        -- :: Exception -> Maybe ArithException
75         errorCalls,             -- :: Exception -> Maybe String
76         dynExceptions,          -- :: Exception -> Maybe Dynamic
77         assertions,             -- :: Exception -> Maybe String
78         asyncExceptions,        -- :: Exception -> Maybe AsyncException
79         userErrors,             -- :: Exception -> Maybe String
80
81         -- * Dynamic exceptions
82
83         -- $dynamic
84         throwDyn,       -- :: Typeable ex => ex -> b
85 #ifdef __GLASGOW_HASKELL__
86         throwDynTo,     -- :: Typeable ex => ThreadId -> ex -> b
87 #endif
88         catchDyn,       -- :: Typeable ex => IO a -> (ex -> IO a) -> IO a
89         
90         -- * Asynchronous Exceptions
91
92         -- $async
93
94         -- ** Asynchronous exception control
95
96         -- |The following two functions allow a thread to control delivery of
97         -- asynchronous exceptions during a critical region.
98
99         block,          -- :: IO a -> IO a
100         unblock,        -- :: IO a -> IO a
101         blocked,        -- :: IO Bool
102
103         -- *** Applying @block@ to an exception handler
104
105         -- $block_handler
106
107         -- *** Interruptible operations
108
109         -- $interruptible
110
111         -- * Assertions
112
113         assert,         -- :: Bool -> a -> a
114
115         -- * Utilities
116
117         bracket,        -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO ()
118         bracket_,       -- :: IO a -> IO b -> IO c -> IO ()
119         bracketOnError,
120
121         finally,        -- :: IO a -> IO b -> IO a
122         
123 #ifdef __GLASGOW_HASKELL__
124         setUncaughtExceptionHandler,      -- :: (Exception -> IO ()) -> IO ()
125         getUncaughtExceptionHandler       -- :: IO (Exception -> IO ())
126 #endif
127   ) where
128
129 #ifdef __GLASGOW_HASKELL__
130 import GHC.Base         ( assert )
131 import GHC.Exception    as ExceptionBase hiding (catch)
132 import GHC.Conc         ( throwTo, ThreadId )
133 import Data.IORef       ( IORef, newIORef, readIORef, writeIORef )
134 import Foreign.C.String ( CString, withCString )
135 import System.IO        ( stdout, hFlush )
136 #endif
137
138 #ifdef __HUGS__
139 import Hugs.Exception   as ExceptionBase
140 #endif
141
142 import Prelude          hiding ( catch )
143 import System.IO.Error  hiding ( catch, try )
144 import System.IO.Unsafe (unsafePerformIO)
145 import Data.Dynamic
146
147 #ifdef __NHC__
148 import qualified System.IO.Error as H'98 (catch)
149 import System.IO.Error (ioError)
150 import IO              (bracket)
151 import DIOError         -- defn of IOError type
152 import System          (ExitCode())
153
154 -- minimum needed for nhc98 to pretend it has Exceptions
155 data Exception   = IOException    IOException
156                  | ArithException ArithException
157                  | ArrayException ArrayException
158                  | AsyncException AsyncException
159                  | ExitException  ExitCode
160 type IOException = IOError
161 data ArithException
162 data ArrayException
163 data AsyncException
164
165 catch    :: IO a -> (Exception -> IO a) -> IO a
166 a `catch` b = a `H'98.catch` (b . IOException)
167
168 throwIO  :: Exception -> IO a
169 throwIO (IOException e) = ioError e
170 throwIO _               = ioError (UserError "Control.Exception.throwIO"
171                                              "unknown exception")
172 throw    :: Exception -> a
173 throw     = unsafePerformIO . throwIO
174
175 evaluate :: a -> IO a
176 evaluate x = x `seq` return x
177
178 ioErrors        :: Exception -> Maybe IOError
179 ioErrors        (IOException e)     = Just e
180 ioErrors        _                   = Nothing
181 arithExceptions :: Exception -> Maybe ArithException
182 arithExceptions (ArithException e)  = Just e
183 arithExceptions _                   = 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 (IOException (UserError _ s)) = Just s
194 userErrors  _                            = Nothing
195
196 assert :: Bool -> a -> a
197 assert True  x = x
198 assert False _ = throw (IOException (UserError "" "Assertion failed"))
199 #endif
200
201 #ifndef __GLASGOW_HASKELL__
202 -- Dummy definitions for implementations lacking asynchonous exceptions
203
204 block   :: IO a -> IO a
205 block    = id
206 unblock :: IO a -> IO a
207 unblock  = id
208 blocked :: IO Bool
209 blocked  = return False
210 #endif
211
212 -----------------------------------------------------------------------------
213 -- Catching exceptions
214
215 -- |This is the simplest of the exception-catching functions.  It
216 -- takes a single argument, runs it, and if an exception is raised
217 -- the \"handler\" is executed, with the value of the exception passed as an
218 -- argument.  Otherwise, the result is returned as normal.  For example:
219 --
220 -- >   catch (openFile f ReadMode) 
221 -- >       (\e -> hPutStr stderr ("Couldn't open "++f++": " ++ show e))
222 --
223 -- For catching exceptions in pure (non-'IO') expressions, see the
224 -- function 'evaluate'.
225 --
226 -- Note that due to Haskell\'s unspecified evaluation order, an
227 -- expression may return one of several possible exceptions: consider
228 -- the expression @error \"urk\" + 1 \`div\` 0@.  Does
229 -- 'catch' execute the handler passing
230 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
231 --
232 -- The answer is \"either\": 'catch' makes a
233 -- non-deterministic choice about which exception to catch.  If you
234 -- call it again, you might get a different exception back.  This is
235 -- ok, because 'catch' is an 'IO' computation.
236 --
237 -- Note that 'catch' catches all types of exceptions, and is generally
238 -- used for \"cleaning up\" before passing on the exception using
239 -- 'throwIO'.  It is not good practice to discard the exception and
240 -- continue, without first checking the type of the exception (it
241 -- might be a 'ThreadKilled', for example).  In this case it is usually better
242 -- to use 'catchJust' and select the kinds of exceptions to catch.
243 --
244 -- Also note that the "Prelude" also exports a function called
245 -- 'Prelude.catch' with a similar type to 'Control.Exception.catch',
246 -- except that the "Prelude" version only catches the IO and user
247 -- families of exceptions (as required by Haskell 98).  
248 --
249 -- We recommend either hiding the "Prelude" version of 'Prelude.catch'
250 -- when importing "Control.Exception": 
251 --
252 -- > import Prelude hiding (catch)
253 --
254 -- or importing "Control.Exception" qualified, to avoid name-clashes:
255 --
256 -- > import qualified Control.Exception as C
257 --
258 -- and then using @C.catch@
259 --
260 #ifndef __NHC__
261 catch   :: IO a                 -- ^ The computation to run
262         -> (Exception -> IO a)  -- ^ Handler to invoke if an exception is raised
263         -> IO a                 
264 catch =  ExceptionBase.catchException
265 #endif
266 -- | The function 'catchJust' is like 'catch', but it takes an extra
267 -- argument which is an /exception predicate/, a function which
268 -- selects which type of exceptions we\'re interested in.  There are
269 -- some predefined exception predicates for useful subsets of
270 -- exceptions: 'ioErrors', 'arithExceptions', and so on.  For example,
271 -- to catch just calls to the 'error' function, we could use
272 --
273 -- >   result <- catchJust errorCalls thing_to_try handler
274 --
275 -- Any other exceptions which are not matched by the predicate
276 -- are re-raised, and may be caught by an enclosing
277 -- 'catch' or 'catchJust'.
278 catchJust
279         :: (Exception -> Maybe b) -- ^ Predicate to select exceptions
280         -> IO a                   -- ^ Computation to run
281         -> (b -> IO a)            -- ^ Handler
282         -> IO a
283 catchJust p a handler = catch a handler'
284   where handler' e = case p e of 
285                         Nothing -> throw e
286                         Just b  -> handler b
287
288 -- | A version of 'catch' with the arguments swapped around; useful in
289 -- situations where the code for the handler is shorter.  For example:
290 --
291 -- >   do handle (\e -> exitWith (ExitFailure 1)) $
292 -- >      ...
293 handle     :: (Exception -> IO a) -> IO a -> IO a
294 handle     =  flip catch
295
296 -- | A version of 'catchJust' with the arguments swapped around (see
297 -- 'handle').
298 handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
299 handleJust p =  flip (catchJust p)
300
301 -----------------------------------------------------------------------------
302 -- 'mapException'
303
304 -- | This function maps one exception into another as proposed in the
305 -- paper \"A semantics for imprecise exceptions\".
306
307 -- Notice that the usage of 'unsafePerformIO' is safe here.
308
309 mapException :: (Exception -> Exception) -> a -> a
310 mapException f v = unsafePerformIO (catch (evaluate v)
311                                           (\x -> throw (f x)))
312
313 -----------------------------------------------------------------------------
314 -- 'try' and variations.
315
316 -- | Similar to 'catch', but returns an 'Either' result which is
317 -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an
318 -- exception was raised and its value is @e@.
319 --
320 -- >  try a = catch (Right `liftM` a) (return . Left)
321 --
322 -- Note: as with 'catch', it is only polite to use this variant if you intend
323 -- to re-throw the exception after performing whatever cleanup is needed.
324 -- Otherwise, 'tryJust' is generally considered to be better.
325 --
326 -- Also note that "System.IO.Error" also exports a function called
327 -- 'System.IO.Error.try' with a similar type to 'Control.Exception.try',
328 -- except that it catches only the IO and user families of exceptions
329 -- (as required by the Haskell 98 @IO@ module).
330
331 try :: IO a -> IO (Either Exception a)
332 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
333
334 -- | A variant of 'try' that takes an exception predicate to select
335 -- which exceptions are caught (c.f. 'catchJust').  If the exception
336 -- does not match the predicate, it is re-thrown.
337 tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a)
338 tryJust p a = do
339   r <- try a
340   case r of
341         Right v -> return (Right v)
342         Left  e -> case p e of
343                         Nothing -> throw e
344                         Just b  -> return (Left b)
345
346 -----------------------------------------------------------------------------
347 -- Dynamic exceptions
348
349 -- $dynamic
350 --  #DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an
351 -- interface for throwing and catching exceptions of type 'Dynamic'
352 -- (see "Data.Dynamic") which allows exception values of any type in
353 -- the 'Typeable' class to be thrown and caught.
354
355 -- | Raise any value as an exception, provided it is in the
356 -- 'Typeable' class.
357 throwDyn :: Typeable exception => exception -> b
358 #ifdef __NHC__
359 throwDyn exception = throw (IOException (UserError "" "dynamic exception"))
360 #else
361 throwDyn exception = throw (DynException (toDyn exception))
362 #endif
363
364 #ifdef __GLASGOW_HASKELL__
365 -- | A variant of 'throwDyn' that throws the dynamic exception to an
366 -- arbitrary thread (GHC only: c.f. 'throwTo').
367 throwDynTo :: Typeable exception => ThreadId -> exception -> IO ()
368 throwDynTo t exception = throwTo t (DynException (toDyn exception))
369 #endif /* __GLASGOW_HASKELL__ */
370
371 -- | Catch dynamic exceptions of the required type.  All other
372 -- exceptions are re-thrown, including dynamic exceptions of the wrong
373 -- type.
374 --
375 -- When using dynamic exceptions it is advisable to define a new
376 -- datatype to use for your exception type, to avoid possible clashes
377 -- with dynamic exceptions used in other libraries.
378 --
379 catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a
380 #ifdef __NHC__
381 catchDyn m k = m        -- can't catch dyn exceptions in nhc98
382 #else
383 catchDyn m k = catchException m handle
384   where handle ex = case ex of
385                            (DynException dyn) ->
386                                 case fromDynamic dyn of
387                                     Just exception  -> k exception
388                                     Nothing -> throw ex
389                            _ -> throw ex
390 #endif
391
392 -----------------------------------------------------------------------------
393 -- Exception Predicates
394
395 -- $preds
396 -- These pre-defined predicates may be used as the first argument to
397 -- 'catchJust', 'tryJust', or 'handleJust' to select certain common
398 -- classes of exceptions.
399 #ifndef __NHC__
400 ioErrors                :: Exception -> Maybe IOError
401 arithExceptions         :: Exception -> Maybe ArithException
402 errorCalls              :: Exception -> Maybe String
403 assertions              :: Exception -> Maybe String
404 dynExceptions           :: Exception -> Maybe Dynamic
405 asyncExceptions         :: Exception -> Maybe AsyncException
406 userErrors              :: Exception -> Maybe String
407
408 ioErrors (IOException e) = Just e
409 ioErrors _ = Nothing
410
411 arithExceptions (ArithException e) = Just e
412 arithExceptions _ = Nothing
413
414 errorCalls (ErrorCall e) = Just e
415 errorCalls _ = Nothing
416
417 assertions (AssertionFailed e) = Just e
418 assertions _ = Nothing
419
420 dynExceptions (DynException e) = Just e
421 dynExceptions _ = Nothing
422
423 asyncExceptions (AsyncException e) = Just e
424 asyncExceptions _ = Nothing
425
426 userErrors (IOException e) | isUserError e = Just (ioeGetErrorString e)
427 userErrors _ = Nothing
428 #endif
429 -----------------------------------------------------------------------------
430 -- Some Useful Functions
431
432 -- | When you want to acquire a resource, do some work with it, and
433 -- then release the resource, it is a good idea to use 'bracket',
434 -- because 'bracket' will install the necessary exception handler to
435 -- release the resource in the event that an exception is raised
436 -- during the computation.  If an exception is raised, then 'bracket' will 
437 -- re-raise the exception (after performing the release).
438 --
439 -- A common example is opening a file:
440 --
441 -- > bracket
442 -- >   (openFile "filename" ReadMode)
443 -- >   (hClose)
444 -- >   (\handle -> do { ... })
445 --
446 -- The arguments to 'bracket' are in this order so that we can partially apply 
447 -- it, e.g.:
448 --
449 -- > withFile name mode = bracket (openFile name mode) hClose
450 --
451 #ifndef __NHC__
452 bracket 
453         :: IO a         -- ^ computation to run first (\"acquire resource\")
454         -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
455         -> (a -> IO c)  -- ^ computation to run in-between
456         -> IO c         -- returns the value from the in-between computation
457 bracket before after thing =
458   block (do
459     a <- before 
460     r <- catch 
461            (unblock (thing a))
462            (\e -> do { after a; throw e })
463     after a
464     return r
465  )
466 #endif
467
468 -- | A specialised variant of 'bracket' with just a computation to run
469 -- afterward.
470 -- 
471 finally :: IO a         -- ^ computation to run first
472         -> IO b         -- ^ computation to run afterward (even if an exception 
473                         -- was raised)
474         -> IO a         -- returns the value from the first computation
475 a `finally` sequel =
476   block (do
477     r <- catch 
478              (unblock a)
479              (\e -> do { sequel; throw e })
480     sequel
481     return r
482   )
483
484 -- | A variant of 'bracket' where the return value from the first computation
485 -- is not required.
486 bracket_ :: IO a -> IO b -> IO c -> IO c
487 bracket_ before after thing = bracket before (const after) (const thing)
488
489 -- | Like bracket, but only performs the final action if there was an 
490 -- exception raised by the in-between computation.
491 bracketOnError
492         :: IO a         -- ^ computation to run first (\"acquire resource\")
493         -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
494         -> (a -> IO c)  -- ^ computation to run in-between
495         -> IO c         -- returns the value from the in-between computation
496 bracketOnError before after thing =
497   block (do
498     a <- before 
499     catch 
500         (unblock (thing a))
501         (\e -> do { after a; throw e })
502  )
503
504 -- -----------------------------------------------------------------------------
505 -- Asynchronous exceptions
506
507 {- $async
508
509  #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
510 external influences, and can be raised at any point during execution.
511 'StackOverflow' and 'HeapOverflow' are two examples of
512 system-generated asynchronous exceptions.
513
514 The primary source of asynchronous exceptions, however, is
515 'throwTo':
516
517 >  throwTo :: ThreadId -> Exception -> IO ()
518
519 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
520 running thread to raise an arbitrary exception in another thread.  The
521 exception is therefore asynchronous with respect to the target thread,
522 which could be doing anything at the time it receives the exception.
523 Great care should be taken with asynchronous exceptions; it is all too
524 easy to introduce race conditions by the over zealous use of
525 'throwTo'.
526 -}
527
528 {- $block_handler
529 There\'s an implied 'block' around every exception handler in a call
530 to one of the 'catch' family of functions.  This is because that is
531 what you want most of the time - it eliminates a common race condition
532 in starting an exception handler, because there may be no exception
533 handler on the stack to handle another exception if one arrives
534 immediately.  If asynchronous exceptions are blocked on entering the
535 handler, though, we have time to install a new exception handler
536 before being interrupted.  If this weren\'t the default, one would have
537 to write something like
538
539 >      block (
540 >           catch (unblock (...))
541 >                      (\e -> handler)
542 >      )
543
544 If you need to unblock asynchronous exceptions again in the exception
545 handler, just use 'unblock' as normal.
546
547 Note that 'try' and friends /do not/ have a similar default, because
548 there is no exception handler in this case.  If you want to use 'try'
549 in an asynchronous-exception-safe way, you will need to use
550 'block'.
551 -}
552
553 {- $interruptible
554
555 Some operations are /interruptible/, which means that they can receive
556 asynchronous exceptions even in the scope of a 'block'.  Any function
557 which may itself block is defined as interruptible; this includes
558 'Control.Concurrent.MVar.takeMVar'
559 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
560 and most operations which perform
561 some I\/O with the outside world.  The reason for having
562 interruptible operations is so that we can write things like
563
564 >      block (
565 >         a <- takeMVar m
566 >         catch (unblock (...))
567 >               (\e -> ...)
568 >      )
569
570 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
571 then this particular
572 combination could lead to deadlock, because the thread itself would be
573 blocked in a state where it can\'t receive any asynchronous exceptions.
574 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
575 safe in the knowledge that the thread can receive exceptions right up
576 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
577 Similar arguments apply for other interruptible operations like
578 'System.IO.openFile'.
579 -}
580
581 #if !(__GLASGOW_HASKELL__ || __NHC__)
582 assert :: Bool -> a -> a
583 assert True x = x
584 assert False _ = throw (AssertionFailed "")
585 #endif
586
587
588 #ifdef __GLASGOW_HASKELL__
589 {-# NOINLINE uncaughtExceptionHandler #-}
590 uncaughtExceptionHandler :: IORef (Exception -> IO ())
591 uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler)
592    where
593       defaultHandler :: Exception -> IO ()
594       defaultHandler ex = do
595          (hFlush stdout) `catchException` (\ _ -> return ())
596          let msg = case ex of
597                Deadlock    -> "no threads to run:  infinite loop or deadlock?"
598                ErrorCall s -> s
599                other       -> showsPrec 0 other ""
600          withCString "%s" $ \cfmt ->
601           withCString msg $ \cmsg ->
602             errorBelch cfmt cmsg
603
604 -- don't use errorBelch() directly, because we cannot call varargs functions
605 -- using the FFI.
606 foreign import ccall unsafe "HsBase.h errorBelch2"
607    errorBelch :: CString -> CString -> IO ()
608
609 setUncaughtExceptionHandler :: (Exception -> IO ()) -> IO ()
610 setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler
611
612 getUncaughtExceptionHandler :: IO (Exception -> IO ())
613 getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler
614 #endif