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