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