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