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