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