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