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