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