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