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