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