[project @ 2002-12-20 18:43:53 by ross]
[packages/old-time.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 #ifdef __GLASGOW_HASKELL__
242 evaluate :: a -> IO a
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 #endif
248
249 -----------------------------------------------------------------------------
250 -- 'mapException'
251
252 -- | This function maps one exception into another as proposed in the
253 -- paper "A semantics for imprecise exceptions".
254
255 -- Notice that the usage of 'unsafePerformIO' is safe here.
256
257 mapException :: (Exception -> Exception) -> a -> a
258 mapException f v = unsafePerformIO (catch (evaluate v)
259 (\x -> throw (f x)))
260
261 -----------------------------------------------------------------------------
262 -- 'try' and variations.
263
264 -- | Similar to 'catch', but returns an 'Either' result which is
265 -- @(Right a)@ if no exception was raised, or @(Left e)@ if an
266 -- exception was raised and its value is @e@.
267 --
268 -- > try a = catch (Right \`liftM\` a) (return . Left)
269 --
270 -- Note: as with 'catch', it is only polite to use this variant if you intend
271 -- to re-throw the exception after performing whatever cleanup is needed.
272 -- Otherwise, 'tryJust' is generally considered to be better.
273 --
274 try :: IO a -> IO (Either Exception a)
275 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
276
277 -- | A variant of 'try' that takes an exception predicate to select
278 -- which exceptions are caught (c.f. 'catchJust'). If the exception
279 -- does not match the predicate, it is re-thrown.
280 tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a)
281 tryJust p a = do
282 r <- try a
283 case r of
284 Right v -> return (Right v)
285 Left e -> case p e of
286 Nothing -> throw e
287 Just b -> return (Left b)
288
289 #ifdef __GLASGOW_HASKELL__
290 -----------------------------------------------------------------------------
291 -- Dynamic exceptions
292
293 -- $dynamic
294 -- #DynamicExceptions# Because the 'Exception' datatype is not extensible, there is an
295 -- interface for throwing and catching exceptions of type 'Dynamic'
296 -- (see "Data.Dynamic") which allows exception values of any type in
297 -- the 'Typeable' class to be thrown and caught.
298
299 -- | Raise any value as an exception, provided it is in the
300 -- 'Typeable' class.
301 throwDyn :: Typeable exception => exception -> b
302 throwDyn exception = throw (DynException (toDyn exception))
303
304 -- | A variant of 'throwDyn' that throws the dynamic exception to an
305 -- arbitrary thread (c.f. 'throwTo').
306 throwDynTo :: Typeable exception => ThreadId -> exception -> IO ()
307 throwDynTo t exception = throwTo t (DynException (toDyn exception))
308
309 -- | Catch dynamic exceptions of the required type. All other
310 -- exceptions are re-thrown, including dynamic exceptions of the wrong
311 -- type.
312 --
313 -- When using dynamic exceptions it is advisable to define a new
314 -- datatype to use for your exception type, to avoid possible clashes
315 -- with dynamic exceptions used in other libraries.
316 --
317 catchDyn :: Typeable exception => IO a -> (exception -> IO a) -> IO a
318 catchDyn m k = catchException m handle
319 where handle ex = case ex of
320 (DynException dyn) ->
321 case fromDynamic dyn of
322 Just exception -> k exception
323 Nothing -> throw ex
324 _ -> throw ex
325 #endif /* __GLASGOW_HASKELL__ */
326
327 -----------------------------------------------------------------------------
328 -- Exception Predicates
329
330 -- $preds
331 -- These pre-defined predicates may be used as the first argument to
332 -- 'catchJust', 'tryJust', or 'handleJust' to select certain common
333 -- classes of exceptions.
334
335 #ifdef __GLASGOW_HASKELL__
336 ioErrors :: Exception -> Maybe IOError
337 arithExceptions :: Exception -> Maybe ArithException
338 errorCalls :: Exception -> Maybe String
339 dynExceptions :: Exception -> Maybe Dynamic
340 assertions :: Exception -> Maybe String
341 asyncExceptions :: Exception -> Maybe AsyncException
342 userErrors :: Exception -> Maybe String
343 #endif /* __GLASGOW_HASKELL__ */
344
345 #ifdef __GLASGOW_HASKELL__
346 ioErrors (IOException e) = Just e
347 ioErrors _ = Nothing
348
349 arithExceptions (ArithException e) = Just e
350 arithExceptions _ = Nothing
351
352 errorCalls (ErrorCall e) = Just e
353 errorCalls _ = Nothing
354
355 assertions (AssertionFailed e) = Just e
356 assertions _ = Nothing
357
358 dynExceptions (DynException e) = Just e
359 dynExceptions _ = Nothing
360
361 asyncExceptions (AsyncException e) = Just e
362 asyncExceptions _ = Nothing
363
364 userErrors (IOException e) | isUserError e = Just (ioeGetErrorString e)
365 userErrors _ = Nothing
366 #endif /* __GLASGOW_HASKELL__ */
367
368 -----------------------------------------------------------------------------
369 -- Some Useful Functions
370
371 -- | When you want to acquire a resource, do some work with it, and
372 -- then release the resource, it is a good idea to use 'bracket',
373 -- because 'bracket' will install the necessary exception handler to
374 -- release the resource in the event that an exception is raised
375 -- during the computation. If an exception is raised, then 'bracket' will
376 -- re-raise the exception (after performing the release).
377 --
378 -- A common example is opening a file:
379 --
380 -- > bracket
381 -- > (openFile "filename" ReadMode)
382 -- > (hClose)
383 -- > (\handle -> do { ... })
384 --
385 -- The arguments to 'bracket' are in this order so that we can partially apply
386 -- it, e.g.:
387 --
388 -- > withFile name = bracket (openFile name) hClose
389 --
390 bracket
391 :: IO a -- ^ computation to run first (\"acquire resource\")
392 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
393 -> (a -> IO c) -- ^ computation to run in-between
394 -> IO c -- returns the value from the in-between computation
395 bracket before after thing =
396 block (do
397 a <- before
398 r <- catch
399 (unblock (thing a))
400 (\e -> do { after a; throw e })
401 after a
402 return r
403 )
404
405
406 -- | A specialised variant of 'bracket' with just a computation to run
407 -- afterward.
408 --
409 finally :: IO a -- ^ computation to run first
410 -> IO b -- ^ computation to run afterward (even if an exception
411 -- was raised)
412 -> IO a -- returns the value from the first computation
413 a `finally` sequel =
414 block (do
415 r <- catch
416 (unblock a)
417 (\e -> do { sequel; throw e })
418 sequel
419 return r
420 )
421
422 -- | A variant of 'bracket' where the return value from the first computation
423 -- is not required.
424 bracket_ :: IO a -> IO b -> IO c -> IO c
425 bracket_ before after thing = bracket before (const after) (const thing)
426
427 -- -----------------------------------------------------------------------------
428 -- Asynchronous exceptions
429
430 {- $async
431
432 #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
433 external influences, and can be raised at any point during execution.
434 'StackOverflow' and 'HeapOverflow' are two examples of
435 system-generated asynchronous exceptions.
436
437 The primary source of asynchronous exceptions, however, is
438 'throwTo':
439
440 > throwTo :: ThreadId -> Exception -> IO ()
441
442 'throwTo' (also 'throwDynTo' and 'Concurrent.killThread') allows one
443 running thread to raise an arbitrary exception in another thread. The
444 exception is therefore asynchronous with respect to the target thread,
445 which could be doing anything at the time it receives the exception.
446 Great care should be taken with asynchronous exceptions; it is all too
447 easy to introduce race conditions by the over zealous use of
448 'throwTo'.
449 -}
450
451 {- $block_handler
452 There\'s an implied 'block' around every exception handler in a call
453 to one of the 'catch' family of functions. This is because that is
454 what you want most of the time - it eliminates a common race condition
455 in starting an exception handler, because there may be no exception
456 handler on the stack to handle another exception if one arrives
457 immediately. If asynchronous exceptions are blocked on entering the
458 handler, though, we have time to install a new exception handler
459 before being interrupted. If this weren\'t the default, one would have
460 to write something like
461
462 > block (
463 > catch (unblock (...))
464 > (\e -> handler)
465 > )
466
467 If you need to unblock asynchronous exceptions again in the exception
468 handler, just use 'unblock' as normal.
469
470 Note that 'try' and friends /do not/ have a similar default, because
471 there is no exception handler in this case. If you want to use 'try'
472 in an asynchronous-exception-safe way, you will need to use
473 'block'.
474 -}
475
476 {- $interruptible
477
478 Some operations are /interruptible/, which means that they can receive
479 asynchronous exceptions even in the scope of a 'block'. Any function
480 which may itself block is defined as interruptible; this includes
481 'takeMVar' (but not 'tryTakeMVar'), and most operations which perform
482 some I\/O with the outside world.. The reason for having
483 interruptible operations is so that we can write things like
484
485 > block (
486 > a <- takeMVar m
487 > catch (unblock (...))
488 > (\e -> ...)
489 > )
490
491 if the 'takeMVar' was not interruptible, then this particular
492 combination could lead to deadlock, because the thread itself would be
493 blocked in a state where it can\'t receive any asynchronous exceptions.
494 With 'takeMVar' interruptible, however, we can be
495 safe in the knowledge that the thread can receive exceptions right up
496 until the point when the 'takeMVar' succeeds.
497 Similar arguments apply for other interruptible operations like
498 'IO.openFile'.
499 -}
500
501 -- -----------------------------------------------------------------------------
502 -- Assert
503
504 #ifdef __HADDOCK__
505 -- | If the first argument evaluates to 'True', then the result is the
506 -- second argument. Otherwise an 'Assertion' exception is raised,
507 -- containing a 'String' with the source file and line number of the
508 -- call to assert.
509 --
510 -- Assertions can normally be turned on or off with a compiler flag
511 -- (for GHC, assertions are normally on unless the @-fignore-asserts@
512 -- option is give). When assertions are turned off, the first
513 -- argument to 'assert' is ignored, and the second argument is
514 -- returned as the result.
515 assert :: Bool -> a -> a
516 #endif
517
518 #ifndef __GLASGOW_HASKELL__
519 assert :: Bool -> a -> a
520 assert True x = x
521 assert False _ = error "Assertion failure"
522 #endif