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