Exception.hs 14 KB
Newer Older
1
{-# LANGUAGE Trustworthy #-}
2
{-# LANGUAGE CPP, NoImplicitPrelude, ExistentialQuantification #-}
3

4
-----------------------------------------------------------------------------
5
-- |
6
7
-- Module      :  Control.Exception
-- Copyright   :  (c) The University of Glasgow 2001
8
-- License     :  BSD-style (see the file libraries/base/LICENSE)
Ian Lynagh's avatar
Ian Lynagh committed
9
--
10
11
-- Maintainer  :  libraries@haskell.org
-- Stability   :  experimental
ross's avatar
ross committed
12
-- Portability :  non-portable (extended exceptions)
13
--
14
15
-- This module provides support for raising and catching both built-in
-- and user-defined exceptions.
16
--
Ross Paterson's avatar
Ross Paterson committed
17
18
19
20
21
22
23
24
25
26
27
28
-- In addition to exceptions thrown by 'IO' operations, exceptions may
-- be thrown by pure code (imprecise exceptions) or by external events
-- (asynchronous exceptions), but may only be caught in the 'IO' monad.
-- For more details, see:
--
--  * /A semantics for imprecise exceptions/, by Simon Peyton Jones,
--    Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson,
--    in /PLDI'99/.
--
--  * /Asynchronous exceptions in Haskell/, by Simon Marlow, Simon Peyton
--    Jones, Andy Moran and John Reppy, in /PLDI'01/.
--
Ian Lynagh's avatar
Ian Lynagh committed
29
30
31
--  * /An Extensible Dynamically-Typed Hierarchy of Exceptions/,
--    by Simon Marlow, in /Haskell '06/.
--
32
33
34
35
-----------------------------------------------------------------------------

module Control.Exception (

Don Stewart's avatar
Don Stewart committed
36
        -- * The Exception type
37
38
39
#ifdef __HUGS__
        SomeException,
#else
40
        SomeException(..),
41
#endif
42
43
44
45
        Exception(..),          -- class
        IOException,            -- instance Eq, Ord, Show, Typeable, Exception
        ArithException(..),     -- instance Eq, Ord, Show, Typeable, Exception
        ArrayException(..),     -- instance Eq, Ord, Show, Typeable, Exception
46
        AssertionFailed(..),
47
        AsyncException(..),     -- instance Eq, Ord, Show, Typeable, Exception
48

49
50
51
#if __GLASGOW_HASKELL__ || __HUGS__
        NonTermination(..),
        NestedAtomically(..),
52
#endif
53
#ifdef __NHC__
Ian Lynagh's avatar
Ian Lynagh committed
54
        System.ExitCode(), -- instance Exception
55
#endif
56

Simon Marlow's avatar
Simon Marlow committed
57
58
        BlockedIndefinitelyOnMVar(..),
        BlockedIndefinitelyOnSTM(..),
59
60
61
62
63
64
        Deadlock(..),
        NoMethodError(..),
        PatternMatchFail(..),
        RecConError(..),
        RecSelError(..),
        RecUpdError(..),
65
        ErrorCall(..),
Don Stewart's avatar
Don Stewart committed
66
67

        -- * Throwing exceptions
Ian Lynagh's avatar
Ian Lynagh committed
68
69
70
        throw,
        throwIO,
        ioError,
ross's avatar
ross committed
71
#ifdef __GLASGOW_HASKELL__
Ian Lynagh's avatar
Ian Lynagh committed
72
        throwTo,
ross's avatar
ross committed
73
#endif
74

Don Stewart's avatar
Don Stewart committed
75
        -- * Catching Exceptions
76

77
78
79
80
81
        -- $catching

        -- ** Catching all exceptions

        -- $catchall
82

Don Stewart's avatar
Don Stewart committed
83
        -- ** The @catch@ functions
Ian Lynagh's avatar
Ian Lynagh committed
84
        catch,
85
        catches, Handler(..),
Ian Lynagh's avatar
Ian Lynagh committed
86
        catchJust,
87

Don Stewart's avatar
Don Stewart committed
88
        -- ** The @handle@ functions
Ian Lynagh's avatar
Ian Lynagh committed
89
90
        handle,
        handleJust,
91

Don Stewart's avatar
Don Stewart committed
92
        -- ** The @try@ functions
Ian Lynagh's avatar
Ian Lynagh committed
93
94
        try,
        tryJust,
95

Don Stewart's avatar
Don Stewart committed
96
        -- ** The @evaluate@ function
Ian Lynagh's avatar
Ian Lynagh committed
97
        evaluate,
98

Don Stewart's avatar
Don Stewart committed
99
        -- ** The @mapException@ function
Ian Lynagh's avatar
Ian Lynagh committed
100
        mapException,
101

Don Stewart's avatar
Don Stewart committed
102
        -- * Asynchronous Exceptions
103

Don Stewart's avatar
Don Stewart committed
104
        -- $async
105

Don Stewart's avatar
Don Stewart committed
106
        -- ** Asynchronous exception control
107

108
        -- |The following functions allow a thread to control delivery of
Don Stewart's avatar
Don Stewart committed
109
        -- asynchronous exceptions during a critical region.
110

111
        mask,
112
#ifndef __NHC__
113
114
115
116
117
        mask_,
        uninterruptibleMask,
        uninterruptibleMask_,
        MaskingState(..),
        getMaskingState,
118
        allowInterrupt,
119
#endif
120
121
122

        -- ** (deprecated) Asynchronous exception control

Ian Lynagh's avatar
Ian Lynagh committed
123
124
125
        block,
        unblock,
        blocked,
126

127
        -- *** Applying @mask@ to an exception handler
128

Don Stewart's avatar
Don Stewart committed
129
        -- $block_handler
130

Don Stewart's avatar
Don Stewart committed
131
        -- *** Interruptible operations
132

Don Stewart's avatar
Don Stewart committed
133
        -- $interruptible
134

Don Stewart's avatar
Don Stewart committed
135
        -- * Assertions
136

Ian Lynagh's avatar
Ian Lynagh committed
137
        assert,
138

Don Stewart's avatar
Don Stewart committed
139
        -- * Utilities
140

Ian Lynagh's avatar
Ian Lynagh committed
141
142
        bracket,
        bracket_,
Don Stewart's avatar
Don Stewart committed
143
        bracketOnError,
144

Ian Lynagh's avatar
Ian Lynagh committed
145
146
147
        finally,
        onException,

148
149
  ) where

150
151
import Control.Exception.Base

152
#ifdef __GLASGOW_HASKELL__
153
import GHC.Base
154
import GHC.IO (unsafeUnmask)
155
import Data.Maybe
Ross Paterson's avatar
Ross Paterson committed
156
157
#else
import Prelude hiding (catch)
158
159
#endif

160
161
162
163
#ifdef __NHC__
import System (ExitCode())
#endif

Ian Lynagh's avatar
Ian Lynagh committed
164
-- | You need this when using 'catches'.
165
data Handler a = forall e . Exception e => Handler (e -> IO a)
166

167
168
169
instance Functor Handler where
     fmap f (Handler h) = Handler (fmap f . h)

Ian Lynagh's avatar
Ian Lynagh committed
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
{- |
Sometimes you want to catch two different sorts of exception. You could
do something like

> f = expr `catch` \ (ex :: ArithException) -> handleArith ex
>          `catch` \ (ex :: IOException)    -> handleIO    ex

However, there are a couple of problems with this approach. The first is
that having two exception handlers is inefficient. However, the more
serious issue is that the second exception handler will catch exceptions
in the first, e.g. in the example above, if @handleArith@ throws an
@IOException@ then the second exception handler will catch it.

Instead, we provide a function 'catches', which would be used thus:

> f = expr `catches` [Handler (\ (ex :: ArithException) -> handleArith ex),
>                     Handler (\ (ex :: IOException)    -> handleIO    ex)]
-}
188
189
190
191
192
193
194
195
196
catches :: IO a -> [Handler a] -> IO a
catches io handlers = io `catch` catchesHandler handlers

catchesHandler :: [Handler a] -> SomeException -> IO a
catchesHandler handlers e = foldr tryHandler (throw e) handlers
    where tryHandler (Handler handler) res
              = case fromException e of
                Just e' -> handler e'
                Nothing -> res
197

198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
-- -----------------------------------------------------------------------------
-- Catching exceptions

{- $catching

There are several functions for catching and examining
exceptions; all of them may only be used from within the
'IO' monad.

Here's a rule of thumb for deciding which catch-style function to
use:

 * If you want to do some cleanup in the event that an exception
   is raised, use 'finally', 'bracket' or 'onException'.

 * To recover after an exception and do something else, the best
   choice is to use one of the 'try' family.

 * ... unless you are recovering from an asynchronous exception, in which
   case use 'catch' or 'catchJust'.

The difference between using 'try' and 'catch' for recovery is that in
'catch' the handler is inside an implicit 'block' (see \"Asynchronous
Exceptions\") which is important when catching asynchronous
exceptions, but when catching other kinds of exception it is
unnecessary.  Furthermore it is possible to accidentally stay inside
the implicit 'block' by tail-calling rather than returning from the
handler, which is why we recommend using 'try' rather than 'catch' for
ordinary exception recovery.

A typical use of 'tryJust' for recovery looks like this:

>  do r <- tryJust (guard . isDoesNotExistError) $ getEnv "HOME"
>     case r of
>       Left  e    -> ...
>       Right home -> ...

-}

237
238
239
-- -----------------------------------------------------------------------------
-- Asynchronous exceptions

240
241
242
243
244
245
246
247
248
249
-- | When invoked inside 'mask', this function allows a blocked
-- asynchronous exception to be raised, if one exists.  It is
-- equivalent to performing an interruptible operation (see
-- #interruptible#), but does not involve any actual blocking.
--
-- When called outside 'mask', or inside 'uninterruptibleMask', this
-- function has no effect.
allowInterrupt :: IO ()
allowInterrupt = unsafeUnmask $ return ()

250
251
{- $async

252
 #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
253
254
255
256
257
258
259
260
261
external influences, and can be raised at any point during execution.
'StackOverflow' and 'HeapOverflow' are two examples of
system-generated asynchronous exceptions.

The primary source of asynchronous exceptions, however, is
'throwTo':

>  throwTo :: ThreadId -> Exception -> IO ()

262
'throwTo' (also 'Control.Concurrent.killThread') allows one
263
264
265
266
267
268
269
270
271
running thread to raise an arbitrary exception in another thread.  The
exception is therefore asynchronous with respect to the target thread,
which could be doing anything at the time it receives the exception.
Great care should be taken with asynchronous exceptions; it is all too
easy to introduce race conditions by the over zealous use of
'throwTo'.
-}

{- $block_handler
272
There\'s an implied 'mask' around every exception handler in a call
273
274
275
276
to one of the 'catch' family of functions.  This is because that is
what you want most of the time - it eliminates a common race condition
in starting an exception handler, because there may be no exception
handler on the stack to handle another exception if one arrives
277
immediately.  If asynchronous exceptions are masked on entering the
278
279
280
281
handler, though, we have time to install a new exception handler
before being interrupted.  If this weren\'t the default, one would have
to write something like

282
>      mask $ \restore ->
283
284
>           catch (restore (...))
>                 (\e -> handler)
285
286

If you need to unblock asynchronous exceptions again in the exception
287
handler, 'restore' can be used there too.
288
289

Note that 'try' and friends /do not/ have a similar default, because
290
291
there is no exception handler in this case.  Don't use 'try' for
recovering from an asynchronous exception.
292
293
294
295
-}

{- $interruptible

296
 #interruptible#
297
Some operations are /interruptible/, which means that they can receive
298
asynchronous exceptions even in the scope of a 'mask'.  Any function
299
which may itself block is defined as interruptible; this includes
ross's avatar
ross committed
300
301
302
303
'Control.Concurrent.MVar.takeMVar'
(but not 'Control.Concurrent.MVar.tryTakeMVar'),
and most operations which perform
some I\/O with the outside world.  The reason for having
304
305
interruptible operations is so that we can write things like

306
>      mask $ \restore -> do
307
>         a <- takeMVar m
308
>         catch (restore (...))
309
310
>               (\e -> ...)

ross's avatar
ross committed
311
312
if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
then this particular
313
314
combination could lead to deadlock, because the thread itself would be
blocked in a state where it can\'t receive any asynchronous exceptions.
ross's avatar
ross committed
315
With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
316
safe in the knowledge that the thread can receive exceptions right up
ross's avatar
ross committed
317
until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
318
Similar arguments apply for other interruptible operations like
ross's avatar
ross committed
319
'System.IO.openFile'.
320
321

It is useful to think of 'mask' not as a way to completely prevent
322
323
asynchronous exceptions, but as a way to switch from asynchronous mode
to polling mode.  The main difficulty with asynchronous
324
325
326
327
exceptions is that they normally can occur anywhere, but within a
'mask' an asynchronous exception is only raised by operations that are
interruptible (or call other interruptible operations).  In many cases
these operations may themselves raise exceptions, such as I\/O errors,
328
329
330
so the caller will usually be prepared to handle exceptions arising from the
operation anyway.  To perfom an explicit poll for asynchronous exceptions
inside 'mask', use 'allowInterrupt'.
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355

Sometimes it is too onerous to handle exceptions in the middle of a
critical piece of stateful code.  There are three ways to handle this
kind of situation:

 * Use STM.  Since a transaction is always either completely executed
   or not at all, transactions are a good way to maintain invariants
   over state in the presence of asynchronous (and indeed synchronous)
   exceptions.

 * Use 'mask', and avoid interruptible operations.  In order to do
   this, we have to know which operations are interruptible.  It is
   impossible to know for any given library function whether it might
   invoke an interruptible operation internally; so instead we give a
   list of guaranteed-not-to-be-interruptible operations below.

 * Use 'uninterruptibleMask'.  This is generally not recommended,
   unless you can guarantee that any interruptible operations invoked
   during the scope of 'uninterruptibleMask' can only ever block for
   a short time.  Otherwise, 'uninterruptibleMask' is a good way to
   make your program deadlock and be unresponsive to user interrupts.

The following operations are guaranteed not to be interruptible:

 * operations on 'IORef' from "Data.IORef"
356

357
 * STM transactions that do not use 'retry'
358

359
 * everything from the @Foreign@ modules
360

361
 * everything from @Control.Exception@
362

363
 * @tryTakeMVar@, @tryPutMVar@, @isEmptyMVar@
364

365
 * @takeMVar@ if the @MVar@ is definitely full, and conversely @putMVar@ if the @MVar@ is definitely empty
366

367
 * @newEmptyMVar@, @newMVar@
368

369
370
 * @forkIO@, @forkIOUnmasked@, @myThreadId@

371
-}
Ian Lynagh's avatar
Ian Lynagh committed
372
373
374
375
376
377
378
379
380
381

{- $catchall

It is possible to catch all exceptions, by using the type 'SomeException':

> catch f (\e -> ... (e :: SomeException) ...)

HOWEVER, this is normally not what you want to do!

For example, suppose you want to read a file, but if it doesn't exist
382
383
384
385
386
387
388
389
then continue as if it contained \"\".  You might be tempted to just
catch all exceptions and return \"\" in the handler. However, this has
all sorts of undesirable consequences.  For example, if the user
presses control-C at just the right moment then the 'UserInterrupt'
exception will be caught, and the program will continue running under
the belief that the file contains \"\".  Similarly, if another thread
tries to kill the thread reading the file then the 'ThreadKilled'
exception will be ignored.
Ian Lynagh's avatar
Ian Lynagh committed
390
391
392
393
394
395

Instead, you should only catch exactly the exceptions that you really
want. In this case, this would likely be more specific than even
\"any IO exception\"; a permissions error would likely also want to be
handled differently. Instead, you would probably want something like:

396
397
> e <- tryJust (guard . isDoesNotExistError) (readFile f)
> let str = either (const "") id e
Ian Lynagh's avatar
Ian Lynagh committed
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415

There are occassions when you really do need to catch any sort of
exception. However, in most cases this is just so you can do some
cleaning up; you aren't actually interested in the exception itself.
For example, if you open a file then you want to close it again,
whether processing the file executes normally or throws an exception.
However, in these cases you can use functions like 'bracket', 'finally'
and 'onException', which never actually pass you the exception, but
just call the cleanup functions at the appropriate points.

But sometimes you really do need to catch any exception, and actually
see what the exception is. One example is at the very top-level of a
program, you may wish to catch any exception, print it to a logfile or
the screen, and then exit gracefully. For these cases, you can use
'catch' (or one of the other exception-catching functions) with the
'SomeException' type.
-}