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