[project @ 2004-02-13 17:46:32 by ross]
[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
10 --
11 -- This module provides support for raising and catching both built-in
12 -- and user-defined exceptions.
13 --
14 -----------------------------------------------------------------------------
15
16 module Control.Exception (
17
18         -- * The Exception type
19         Exception(..),          -- instance Eq, Ord, Show, Typeable
20         IOException,            -- instance Eq, Ord, Show, Typeable
21         ArithException(..),     -- instance Eq, Ord, Show, Typeable
22         ArrayException(..),     -- instance Eq, Ord, Show, Typeable
23         AsyncException(..),     -- instance Eq, Ord, Show, Typeable
24
25         -- * Throwing exceptions
26         throwIO,        -- :: Exception -> IO a
27         throw,          -- :: Exception -> a
28         ioError,        -- :: IOError -> IO a
29 #ifdef __GLASGOW_HASKELL__
30         throwTo,        -- :: ThreadId -> Exception -> a
31 #endif
32
33         -- * Catching Exceptions
34
35         -- |There are several functions for catching and examining
36         -- exceptions; all of them may only be used from within the
37         -- 'IO' monad.
38
39         -- ** The @catch@ functions
40         catch,     -- :: IO a -> (Exception -> IO a) -> IO a
41         catchJust, -- :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a
42
43         -- ** The @handle@ functions
44         handle,    -- :: (Exception -> IO a) -> IO a -> IO a
45         handleJust,-- :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
46
47         -- ** The @try@ functions
48         try,       -- :: IO a -> IO (Either Exception a)
49         tryJust,   -- :: (Exception -> Maybe b) -> a    -> IO (Either b a)
50
51         -- ** The @evaluate@ function
52         evaluate,  -- :: a -> IO a
53
54         -- ** The @mapException@ function
55         mapException,           -- :: (Exception -> Exception) -> a -> a
56
57         -- ** Exception predicates
58         
59         -- $preds
60
61         ioErrors,               -- :: Exception -> Maybe IOError
62         arithExceptions,        -- :: Exception -> Maybe ArithException
63         errorCalls,             -- :: Exception -> Maybe String
64         dynExceptions,          -- :: Exception -> Maybe Dynamic
65         assertions,             -- :: Exception -> Maybe String
66         asyncExceptions,        -- :: Exception -> Maybe AsyncException
67         userErrors,             -- :: Exception -> Maybe String
68
69         -- * Dynamic exceptions
70
71         -- $dynamic
72         throwDyn,       -- :: Typeable ex => ex -> b
73 #ifdef __GLASGOW_HASKELL__
74         throwDynTo,     -- :: Typeable ex => ThreadId -> ex -> b
75 #endif
76         catchDyn,       -- :: Typeable ex => IO a -> (ex -> IO a) -> IO a
77         
78         -- * Asynchronous Exceptions
79
80         -- $async
81
82         -- ** Asynchronous exception control
83
84         -- |The following two functions allow a thread to control delivery of
85         -- asynchronous exceptions during a critical region.
86
87         block,          -- :: IO a -> IO a
88         unblock,        -- :: IO a -> IO a
89
90         -- *** Applying @block@ to an exception handler
91
92         -- $block_handler
93
94         -- *** Interruptible operations
95
96         -- $interruptible
97
98         -- * Assertions
99
100         assert,         -- :: Bool -> a -> a
101
102         -- * Utilities
103
104         bracket,        -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO ()
105         bracket_,       -- :: IO a -> IO b -> IO c -> IO ()
106
107         finally,        -- :: IO a -> IO b -> IO a
108         
109 #ifdef __GLASGOW_HASKELL__
110         setUncaughtExceptionHandler,      -- :: (Exception -> IO ()) -> IO ()
111         getUncaughtExceptionHandler       -- :: IO (Exception -> IO ())
112 #endif
113   ) where
114
115 #ifdef __GLASGOW_HASKELL__
116 import GHC.Base         ( assert )
117 import GHC.Exception    as ExceptionBase hiding (catch)
118 import GHC.Conc         ( throwTo, ThreadId )
119 import GHC.IOBase       ( IO(..), IORef(..), newIORef, readIORef, writeIORef )
120 import GHC.Handle       ( stdout, hFlush )
121 import Foreign.C.String ( CString, withCStringLen )
122 #endif
123
124 #ifdef __HUGS__
125 import Hugs.Exception   as ExceptionBase
126 #endif
127
128 import Prelude          hiding ( catch )
129 import System.IO.Error  hiding ( catch, try )
130 import System.IO.Unsafe (unsafePerformIO)
131 import Data.Dynamic
132
133 #include "Typeable.h"
134 INSTANCE_TYPEABLE0(Exception,exceptionTc,"Exception")
135 INSTANCE_TYPEABLE0(IOException,ioExceptionTc,"IOException")
136 INSTANCE_TYPEABLE0(ArithException,arithExceptionTc,"ArithException")
137 INSTANCE_TYPEABLE0(ArrayException,arrayExceptionTc,"ArrayException")
138 INSTANCE_TYPEABLE0(AsyncException,asyncExceptionTc,"AsyncException")
139
140 -----------------------------------------------------------------------------
141 -- Catching exceptions
142
143 -- |This is the simplest of the exception-catching functions.  It
144 -- takes a single argument, runs it, and if an exception is raised
145 -- the \"handler\" is executed, with the value of the exception passed as an
146 -- argument.  Otherwise, the result is returned as normal.  For example:
147 --
148 -- >   catch (openFile f ReadMode) 
149 -- >       (\e -> hPutStr stderr (\"Couldn\'t open \"++f++\": \" ++ show e))
150 --
151 -- For catching exceptions in pure (non-'IO') expressions, see the
152 -- function 'evaluate'.
153 --
154 -- Note that due to Haskell\'s unspecified evaluation order, an
155 -- expression may return one of several possible exceptions: consider
156 -- the expression @error \"urk\" + 1 \`div\` 0@.  Does
157 -- 'catch' execute the handler passing
158 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
159 --
160 -- The answer is \"either\": 'catch' makes a
161 -- non-deterministic choice about which exception to catch.  If you
162 -- call it again, you might get a different exception back.  This is
163 -- ok, because 'catch' is an 'IO' computation.
164 --
165 -- Note that 'catch' catches all types of exceptions, and is generally
166 -- used for \"cleaning up\" before passing on the exception using
167 -- 'throwIO'.  It is not good practice to discard the exception and
168 -- continue, without first checking the type of the exception (it
169 -- might be a 'ThreadKilled', for example).  In this case it is usually better
170 -- to use 'catchJust' and select the kinds of exceptions to catch.
171 --
172 -- Also note that The "Prelude" also exports a
173 -- function called 'catch' which has the same type as
174 -- 'Control.Exception.catch', the difference being that the
175 -- "Prelude" version only catches the IO and user
176 -- families of exceptions (as required by Haskell 98).  We recommend
177 -- either hiding the "Prelude" version of
178 -- 'catch' when importing
179 -- "Control.Exception", or importing
180 -- "Control.Exception" qualified, to avoid name-clashes.
181
182 catch   :: IO a                 -- ^ The computation to run
183         -> (Exception -> IO a)  -- ^ Handler to invoke if an exception is raised
184         -> IO a                 
185 catch =  ExceptionBase.catchException
186
187 -- | The function 'catchJust' is like 'catch', but it takes an extra
188 -- argument which is an /exception predicate/, a function which
189 -- selects which type of exceptions we\'re interested in.  There are
190 -- some predefined exception predicates for useful subsets of
191 -- exceptions: 'ioErrors', 'arithExceptions', and so on.  For example,
192 -- to catch just calls to the 'error' function, we could use
193 --
194 -- >   result <- catchJust errorCalls thing_to_try handler
195 --
196 -- Any other exceptions which are not matched by the predicate
197 -- are re-raised, and may be caught by an enclosing
198 -- 'catch' or 'catchJust'.
199 catchJust
200         :: (Exception -> Maybe b) -- ^ Predicate to select exceptions
201         -> IO a                   -- ^ Computation to run
202         -> (b -> IO a)            -- ^ Handler
203         -> IO a
204 catchJust p a handler = catch a handler'
205   where handler' e = case p e of 
206                         Nothing -> throw e
207                         Just b  -> handler b
208
209 -- | A version of 'catch' with the arguments swapped around; useful in
210 -- situations where the code for the handler is shorter.  For example:
211 --
212 -- >   do handle (\e -> exitWith (ExitFailure 1)) $
213 -- >      ...
214 handle     :: (Exception -> IO a) -> IO a -> IO a
215 handle     =  flip catch
216
217 -- | A version of 'catchJust' with the arguments swapped around (see
218 -- 'handle').
219 handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
220 handleJust p =  flip (catchJust p)
221
222 -----------------------------------------------------------------------------
223 -- evaluate
224
225 -- | Forces its argument to be evaluated, and returns the result in
226 -- the 'IO' monad.  It can be used to order evaluation with respect to
227 -- other 'IO' operations; its semantics are given by
228 --
229 -- >   evaluate undefined `seq` return ()  ==> return ()
230 -- >   catch (evaluate undefined) (\e -> return ())  ==> return ()
231 --
232 -- NOTE: @(evaluate a)@ is /not/ the same as @(a \`seq\` return a)@.
233 #ifdef __GLASGOW_HASKELL__
234 evaluate :: a -> IO a
235 evaluate a = IO $ \s -> case a `seq` () of () -> (# s, a #)
236         -- NB. can't write  
237         --      a `seq` (# s, a #)
238         -- because we can't have an unboxed tuple as a function argument
239 #endif
240
241 -----------------------------------------------------------------------------
242 -- 'mapException'
243
244 -- | This function maps one exception into another as proposed in the
245 -- paper \"A semantics for imprecise exceptions\".
246
247 -- Notice that the usage of 'unsafePerformIO' is safe here.
248
249 mapException :: (Exception -> Exception) -> a -> a
250 mapException f v = unsafePerformIO (catch (evaluate v)
251                                           (\x -> throw (f x)))
252
253 -----------------------------------------------------------------------------
254 -- 'try' and variations.
255
256 -- | Similar to 'catch', but returns an 'Either' result which is
257 -- @(Right a)@ if no exception was raised, or @(Left e)@ if an
258 -- exception was raised and its value is @e@.
259 --
260 -- >  try a = catch (Right \`liftM\` a) (return . Left)
261 --
262 -- Note: as with 'catch', it is only polite to use this variant if you intend
263 -- to re-throw the exception after performing whatever cleanup is needed.
264 -- Otherwise, 'tryJust' is generally considered to be better.
265 --
266 try :: IO a -> IO (Either Exception a)
267 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
268
269 -- | A variant of 'try' that takes an exception predicate to select
270 -- which exceptions are caught (c.f. 'catchJust').  If the exception
271 -- does not match the predicate, it is re-thrown.
272 tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a)
273 tryJust p a = do
274   r <- try a
275   case r of
276         Right v -> return (Right v)
277         Left  e -> case p e of
278                         Nothing -> throw e
279                         Just b  -> return (Left b)
280
281 -----------------------------------------------------------------------------
282 -- Dynamic exceptions
283
284 -- $dynamic
285 --  #DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an
286 -- interface for throwing and catching exceptions of type 'Dynamic'
287 -- (see "Data.Dynamic") which allows exception values of any type in
288 -- the 'Typeable' class to be thrown and caught.
289
290 -- | Raise any value as an exception, provided it is in the
291 -- 'Typeable' class.
292 throwDyn :: Typeable exception => exception -> b
293 throwDyn exception = throw (DynException (toDyn exception))
294
295 #ifdef __GLASGOW_HASKELL__
296 -- | A variant of 'throwDyn' that throws the dynamic exception to an
297 -- arbitrary thread (GHC only: c.f. 'throwTo').
298 throwDynTo :: Typeable exception => ThreadId -> exception -> IO ()
299 throwDynTo t exception = throwTo t (DynException (toDyn exception))
300 #endif /* __GLASGOW_HASKELL__ */
301
302 -- | Catch dynamic exceptions of the required type.  All other
303 -- exceptions are re-thrown, including dynamic exceptions of the wrong
304 -- type.
305 --
306 -- When using dynamic exceptions it is advisable to define a new
307 -- datatype to use for your exception type, to avoid possible clashes
308 -- with dynamic exceptions used in other libraries.
309 --
310 catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a
311 catchDyn m k = catchException m handle
312   where handle ex = case ex of
313                            (DynException dyn) ->
314                                 case fromDynamic dyn of
315                                     Just exception  -> k exception
316                                     Nothing -> throw ex
317                            _ -> throw ex
318
319 -----------------------------------------------------------------------------
320 -- Exception Predicates
321
322 -- $preds
323 -- These pre-defined predicates may be used as the first argument to
324 -- 'catchJust', 'tryJust', or 'handleJust' to select certain common
325 -- classes of exceptions.
326
327 ioErrors                :: Exception -> Maybe IOError
328 arithExceptions         :: Exception -> Maybe ArithException
329 errorCalls              :: Exception -> Maybe String
330 assertions              :: Exception -> Maybe String
331 dynExceptions           :: Exception -> Maybe Dynamic
332 asyncExceptions         :: Exception -> Maybe AsyncException
333 userErrors              :: Exception -> Maybe String
334
335 ioErrors (IOException e) = Just e
336 ioErrors _ = Nothing
337
338 arithExceptions (ArithException e) = Just e
339 arithExceptions _ = Nothing
340
341 errorCalls (ErrorCall e) = Just e
342 errorCalls _ = Nothing
343
344 assertions (AssertionFailed e) = Just e
345 assertions _ = Nothing
346
347 dynExceptions (DynException e) = Just e
348 dynExceptions _ = Nothing
349
350 asyncExceptions (AsyncException e) = Just e
351 asyncExceptions _ = Nothing
352
353 userErrors (IOException e) | isUserError e = Just (ioeGetErrorString e)
354 userErrors _ = Nothing
355
356 -----------------------------------------------------------------------------
357 -- Some Useful Functions
358
359 -- | When you want to acquire a resource, do some work with it, and
360 -- then release the resource, it is a good idea to use 'bracket',
361 -- because 'bracket' will install the necessary exception handler to
362 -- release the resource in the event that an exception is raised
363 -- during the computation.  If an exception is raised, then 'bracket' will 
364 -- re-raise the exception (after performing the release).
365 --
366 -- A common example is opening a file:
367 --
368 -- > bracket
369 -- >   (openFile "filename" ReadMode)
370 -- >   (hClose)
371 -- >   (\handle -> do { ... })
372 --
373 -- The arguments to 'bracket' are in this order so that we can partially apply 
374 -- it, e.g.:
375 --
376 -- > withFile name = bracket (openFile name) hClose
377 --
378 bracket 
379         :: IO a         -- ^ computation to run first (\"acquire resource\")
380         -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
381         -> (a -> IO c)  -- ^ computation to run in-between
382         -> IO c         -- returns the value from the in-between computation
383 bracket before after thing =
384   block (do
385     a <- before 
386     r <- catch 
387            (unblock (thing a))
388            (\e -> do { after a; throw e })
389     after a
390     return r
391  )
392    
393
394 -- | A specialised variant of 'bracket' with just a computation to run
395 -- afterward.
396 -- 
397 finally :: IO a         -- ^ computation to run first
398         -> IO b         -- ^ computation to run afterward (even if an exception 
399                         -- was raised)
400         -> IO a         -- returns the value from the first computation
401 a `finally` sequel =
402   block (do
403     r <- catch 
404              (unblock a)
405              (\e -> do { sequel; throw e })
406     sequel
407     return r
408   )
409
410 -- | A variant of 'bracket' where the return value from the first computation
411 -- is not required.
412 bracket_ :: IO a -> IO b -> IO c -> IO c
413 bracket_ before after thing = bracket before (const after) (const thing)
414
415 -- -----------------------------------------------------------------------------
416 -- Asynchronous exceptions
417
418 {- $async
419
420  #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
421 external influences, and can be raised at any point during execution.
422 'StackOverflow' and 'HeapOverflow' are two examples of
423 system-generated asynchronous exceptions.
424
425 The primary source of asynchronous exceptions, however, is
426 'throwTo':
427
428 >  throwTo :: ThreadId -> Exception -> IO ()
429
430 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
431 running thread to raise an arbitrary exception in another thread.  The
432 exception is therefore asynchronous with respect to the target thread,
433 which could be doing anything at the time it receives the exception.
434 Great care should be taken with asynchronous exceptions; it is all too
435 easy to introduce race conditions by the over zealous use of
436 'throwTo'.
437 -}
438
439 {- $block_handler
440 There\'s an implied 'block' around every exception handler in a call
441 to one of the 'catch' family of functions.  This is because that is
442 what you want most of the time - it eliminates a common race condition
443 in starting an exception handler, because there may be no exception
444 handler on the stack to handle another exception if one arrives
445 immediately.  If asynchronous exceptions are blocked on entering the
446 handler, though, we have time to install a new exception handler
447 before being interrupted.  If this weren\'t the default, one would have
448 to write something like
449
450 >      block (
451 >           catch (unblock (...))
452 >                      (\e -> handler)
453 >      )
454
455 If you need to unblock asynchronous exceptions again in the exception
456 handler, just use 'unblock' as normal.
457
458 Note that 'try' and friends /do not/ have a similar default, because
459 there is no exception handler in this case.  If you want to use 'try'
460 in an asynchronous-exception-safe way, you will need to use
461 'block'.
462 -}
463
464 {- $interruptible
465
466 Some operations are /interruptible/, which means that they can receive
467 asynchronous exceptions even in the scope of a 'block'.  Any function
468 which may itself block is defined as interruptible; this includes
469 'Control.Concurrent.MVar.takeMVar'
470 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
471 and most operations which perform
472 some I\/O with the outside world.  The reason for having
473 interruptible operations is so that we can write things like
474
475 >      block (
476 >         a <- takeMVar m
477 >         catch (unblock (...))
478 >               (\e -> ...)
479 >      )
480
481 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
482 then this particular
483 combination could lead to deadlock, because the thread itself would be
484 blocked in a state where it can\'t receive any asynchronous exceptions.
485 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
486 safe in the knowledge that the thread can receive exceptions right up
487 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
488 Similar arguments apply for other interruptible operations like
489 'System.IO.openFile'.
490 -}
491
492 -- -----------------------------------------------------------------------------
493 -- Assert
494
495 #ifdef __HADDOCK__
496 -- | If the first argument evaluates to 'True', then the result is the
497 -- second argument.  Otherwise an 'AssertionFailed' exception is raised,
498 -- containing a 'String' with the source file and line number of the
499 -- call to assert.
500 --
501 -- Assertions can normally be turned on or off with a compiler flag
502 -- (for GHC, assertions are normally on unless the @-fignore-asserts@
503 -- option is give).  When assertions are turned off, the first
504 -- argument to 'assert' is ignored, and the second argument is
505 -- returned as the result.
506 assert :: Bool -> a -> a
507 #endif
508
509 #ifndef __GLASGOW_HASKELL__
510 assert :: Bool -> a -> a
511 assert True x = x
512 assert False _ = throw (AssertionFailed "")
513 #endif
514
515
516 #ifdef __GLASGOW_HASKELL__
517 {-# NOINLINE uncaughtExceptionHandler #-}
518 uncaughtExceptionHandler :: IORef (Exception -> IO ())
519 uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler)
520    where
521       defaultHandler :: Exception -> IO ()
522       defaultHandler ex = do
523          (hFlush stdout) `catchException` (\ _ -> return ())
524          let msg = case ex of
525                Deadlock    -> "no threads to run:  infinite loop or deadlock?"
526                ErrorCall s -> s
527                other       -> showsPrec 0 other "\n"
528          withCStringLen ("Fail: "++msg) $ \(cstr,len) -> writeErrString cstr len
529          
530 foreign import ccall unsafe "writeErrString__"
531         writeErrString :: CString -> Int -> IO ()
532
533 setUncaughtExceptionHandler :: (Exception -> IO ()) -> IO ()
534 setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler
535
536 getUncaughtExceptionHandler :: IO (Exception -> IO ())
537 getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler
538 #endif