b2b8b61343361e1e89d7ea0321f86b37ce352982
[packages/base.git] / Control / Exception.hs
1 {-# LANGUAGE Trustworthy #-}
2 {-# LANGUAGE CPP, NoImplicitPrelude, ExistentialQuantification #-}
3
4 -----------------------------------------------------------------------------
5 -- |
6 -- Module : Control.Exception
7 -- Copyright : (c) The University of Glasgow 2001
8 -- License : BSD-style (see the file libraries/base/LICENSE)
9 --
10 -- Maintainer : libraries@haskell.org
11 -- Stability : experimental
12 -- Portability : non-portable (extended exceptions)
13 --
14 -- This module provides support for raising and catching both built-in
15 -- and user-defined exceptions.
16 --
17 -- In addition to exceptions thrown by 'IO' operations, exceptions may
18 -- be thrown by pure code (imprecise exceptions) or by external events
19 -- (asynchronous exceptions), but may only be caught in the 'IO' monad.
20 -- For more details, see:
21 --
22 -- * /A semantics for imprecise exceptions/, by Simon Peyton Jones,
23 -- Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson,
24 -- in /PLDI'99/.
25 --
26 -- * /Asynchronous exceptions in Haskell/, by Simon Marlow, Simon Peyton
27 -- Jones, Andy Moran and John Reppy, in /PLDI'01/.
28 --
29 -- * /An Extensible Dynamically-Typed Hierarchy of Exceptions/,
30 -- by Simon Marlow, in /Haskell '06/.
31 --
32 -----------------------------------------------------------------------------
33
34 module Control.Exception (
35
36 -- * The Exception type
37 #ifdef __HUGS__
38 SomeException,
39 #else
40 SomeException(..),
41 #endif
42 Exception(..), -- class
43 IOException, -- instance Eq, Ord, Show, Typeable, Exception
44 ArithException(..), -- instance Eq, Ord, Show, Typeable, Exception
45 ArrayException(..), -- instance Eq, Ord, Show, Typeable, Exception
46 AssertionFailed(..),
47 SomeAsyncException(..),
48 AsyncException(..), -- instance Eq, Ord, Show, Typeable, Exception
49 asyncExceptionToException, asyncExceptionFromException,
50
51 #if __GLASGOW_HASKELL__ || __HUGS__
52 NonTermination(..),
53 NestedAtomically(..),
54 #endif
55
56 BlockedIndefinitelyOnMVar(..),
57 BlockedIndefinitelyOnSTM(..),
58 Deadlock(..),
59 NoMethodError(..),
60 PatternMatchFail(..),
61 RecConError(..),
62 RecSelError(..),
63 RecUpdError(..),
64 ErrorCall(..),
65
66 -- * Throwing exceptions
67 throw,
68 throwIO,
69 ioError,
70 #ifdef __GLASGOW_HASKELL__
71 throwTo,
72 #endif
73
74 -- * Catching Exceptions
75
76 -- $catching
77
78 -- ** Catching all exceptions
79
80 -- $catchall
81
82 -- ** The @catch@ functions
83 catch,
84 catches, Handler(..),
85 catchJust,
86
87 -- ** The @handle@ functions
88 handle,
89 handleJust,
90
91 -- ** The @try@ functions
92 try,
93 tryJust,
94
95 -- ** The @evaluate@ function
96 evaluate,
97
98 -- ** The @mapException@ function
99 mapException,
100
101 -- * Asynchronous Exceptions
102
103 -- $async
104
105 -- ** Asynchronous exception control
106
107 -- |The following functions allow a thread to control delivery of
108 -- asynchronous exceptions during a critical region.
109
110 mask,
111 mask_,
112 uninterruptibleMask,
113 uninterruptibleMask_,
114 MaskingState(..),
115 getMaskingState,
116 allowInterrupt,
117
118 -- *** Applying @mask@ to an exception handler
119
120 -- $block_handler
121
122 -- *** Interruptible operations
123
124 -- $interruptible
125
126 -- * Assertions
127
128 assert,
129
130 -- * Utilities
131
132 bracket,
133 bracket_,
134 bracketOnError,
135
136 finally,
137 onException,
138
139 ) where
140
141 import Control.Exception.Base
142
143 #ifdef __GLASGOW_HASKELL__
144 import GHC.Base
145 import GHC.IO (unsafeUnmask)
146 import Data.Maybe
147 #else
148 import Prelude hiding (catch)
149 #endif
150
151 -- | You need this when using 'catches'.
152 data Handler a = forall e . Exception e => Handler (e -> IO a)
153
154 instance Functor Handler where
155 fmap f (Handler h) = Handler (fmap f . h)
156
157 {- |
158 Sometimes you want to catch two different sorts of exception. You could
159 do something like
160
161 > f = expr `catch` \ (ex :: ArithException) -> handleArith ex
162 > `catch` \ (ex :: IOException) -> handleIO ex
163
164 However, there are a couple of problems with this approach. The first is
165 that having two exception handlers is inefficient. However, the more
166 serious issue is that the second exception handler will catch exceptions
167 in the first, e.g. in the example above, if @handleArith@ throws an
168 @IOException@ then the second exception handler will catch it.
169
170 Instead, we provide a function 'catches', which would be used thus:
171
172 > f = expr `catches` [Handler (\ (ex :: ArithException) -> handleArith ex),
173 > Handler (\ (ex :: IOException) -> handleIO ex)]
174 -}
175 catches :: IO a -> [Handler a] -> IO a
176 catches io handlers = io `catch` catchesHandler handlers
177
178 catchesHandler :: [Handler a] -> SomeException -> IO a
179 catchesHandler handlers e = foldr tryHandler (throw e) handlers
180 where tryHandler (Handler handler) res
181 = case fromException e of
182 Just e' -> handler e'
183 Nothing -> res
184
185 -- -----------------------------------------------------------------------------
186 -- Catching exceptions
187
188 {- $catching
189
190 There are several functions for catching and examining
191 exceptions; all of them may only be used from within the
192 'IO' monad.
193
194 Here's a rule of thumb for deciding which catch-style function to
195 use:
196
197 * If you want to do some cleanup in the event that an exception
198 is raised, use 'finally', 'bracket' or 'onException'.
199
200 * To recover after an exception and do something else, the best
201 choice is to use one of the 'try' family.
202
203 * ... unless you are recovering from an asynchronous exception, in which
204 case use 'catch' or 'catchJust'.
205
206 The difference between using 'try' and 'catch' for recovery is that in
207 'catch' the handler is inside an implicit 'block' (see \"Asynchronous
208 Exceptions\") which is important when catching asynchronous
209 exceptions, but when catching other kinds of exception it is
210 unnecessary. Furthermore it is possible to accidentally stay inside
211 the implicit 'block' by tail-calling rather than returning from the
212 handler, which is why we recommend using 'try' rather than 'catch' for
213 ordinary exception recovery.
214
215 A typical use of 'tryJust' for recovery looks like this:
216
217 > do r <- tryJust (guard . isDoesNotExistError) $ getEnv "HOME"
218 > case r of
219 > Left e -> ...
220 > Right home -> ...
221
222 -}
223
224 -- -----------------------------------------------------------------------------
225 -- Asynchronous exceptions
226
227 -- | When invoked inside 'mask', this function allows a blocked
228 -- asynchronous exception to be raised, if one exists. It is
229 -- equivalent to performing an interruptible operation (see
230 -- #interruptible#), but does not involve any actual blocking.
231 --
232 -- When called outside 'mask', or inside 'uninterruptibleMask', this
233 -- function has no effect.
234 allowInterrupt :: IO ()
235 allowInterrupt = unsafeUnmask $ return ()
236
237 {- $async
238
239 #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
240 external influences, and can be raised at any point during execution.
241 'StackOverflow' and 'HeapOverflow' are two examples of
242 system-generated asynchronous exceptions.
243
244 The primary source of asynchronous exceptions, however, is
245 'throwTo':
246
247 > throwTo :: ThreadId -> Exception -> IO ()
248
249 'throwTo' (also 'Control.Concurrent.killThread') allows one
250 running thread to raise an arbitrary exception in another thread. The
251 exception is therefore asynchronous with respect to the target thread,
252 which could be doing anything at the time it receives the exception.
253 Great care should be taken with asynchronous exceptions; it is all too
254 easy to introduce race conditions by the over zealous use of
255 'throwTo'.
256 -}
257
258 {- $block_handler
259 There\'s an implied 'mask' around every exception handler in a call
260 to one of the 'catch' family of functions. This is because that is
261 what you want most of the time - it eliminates a common race condition
262 in starting an exception handler, because there may be no exception
263 handler on the stack to handle another exception if one arrives
264 immediately. If asynchronous exceptions are masked on entering the
265 handler, though, we have time to install a new exception handler
266 before being interrupted. If this weren\'t the default, one would have
267 to write something like
268
269 > mask $ \restore ->
270 > catch (restore (...))
271 > (\e -> handler)
272
273 If you need to unblock asynchronous exceptions again in the exception
274 handler, 'restore' can be used there too.
275
276 Note that 'try' and friends /do not/ have a similar default, because
277 there is no exception handler in this case. Don't use 'try' for
278 recovering from an asynchronous exception.
279 -}
280
281 {- $interruptible
282
283 #interruptible#
284 Some operations are /interruptible/, which means that they can receive
285 asynchronous exceptions even in the scope of a 'mask'. Any function
286 which may itself block is defined as interruptible; this includes
287 'Control.Concurrent.MVar.takeMVar'
288 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
289 and most operations which perform
290 some I\/O with the outside world. The reason for having
291 interruptible operations is so that we can write things like
292
293 > mask $ \restore -> do
294 > a <- takeMVar m
295 > catch (restore (...))
296 > (\e -> ...)
297
298 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
299 then this particular
300 combination could lead to deadlock, because the thread itself would be
301 blocked in a state where it can\'t receive any asynchronous exceptions.
302 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
303 safe in the knowledge that the thread can receive exceptions right up
304 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
305 Similar arguments apply for other interruptible operations like
306 'System.IO.openFile'.
307
308 It is useful to think of 'mask' not as a way to completely prevent
309 asynchronous exceptions, but as a way to switch from asynchronous mode
310 to polling mode. The main difficulty with asynchronous
311 exceptions is that they normally can occur anywhere, but within a
312 'mask' an asynchronous exception is only raised by operations that are
313 interruptible (or call other interruptible operations). In many cases
314 these operations may themselves raise exceptions, such as I\/O errors,
315 so the caller will usually be prepared to handle exceptions arising from the
316 operation anyway. To perfom an explicit poll for asynchronous exceptions
317 inside 'mask', use 'allowInterrupt'.
318
319 Sometimes it is too onerous to handle exceptions in the middle of a
320 critical piece of stateful code. There are three ways to handle this
321 kind of situation:
322
323 * Use STM. Since a transaction is always either completely executed
324 or not at all, transactions are a good way to maintain invariants
325 over state in the presence of asynchronous (and indeed synchronous)
326 exceptions.
327
328 * Use 'mask', and avoid interruptible operations. In order to do
329 this, we have to know which operations are interruptible. It is
330 impossible to know for any given library function whether it might
331 invoke an interruptible operation internally; so instead we give a
332 list of guaranteed-not-to-be-interruptible operations below.
333
334 * Use 'uninterruptibleMask'. This is generally not recommended,
335 unless you can guarantee that any interruptible operations invoked
336 during the scope of 'uninterruptibleMask' can only ever block for
337 a short time. Otherwise, 'uninterruptibleMask' is a good way to
338 make your program deadlock and be unresponsive to user interrupts.
339
340 The following operations are guaranteed not to be interruptible:
341
342 * operations on 'IORef' from "Data.IORef"
343
344 * STM transactions that do not use 'retry'
345
346 * everything from the @Foreign@ modules
347
348 * everything from @Control.Exception@ except for 'throwTo'
349
350 * @tryTakeMVar@, @tryPutMVar@, @isEmptyMVar@
351
352 * @takeMVar@ if the @MVar@ is definitely full, and conversely @putMVar@ if the @MVar@ is definitely empty
353
354 * @newEmptyMVar@, @newMVar@
355
356 * @forkIO@, @forkIOUnmasked@, @myThreadId@
357
358 -}
359
360 {- $catchall
361
362 It is possible to catch all exceptions, by using the type 'SomeException':
363
364 > catch f (\e -> ... (e :: SomeException) ...)
365
366 HOWEVER, this is normally not what you want to do!
367
368 For example, suppose you want to read a file, but if it doesn't exist
369 then continue as if it contained \"\". You might be tempted to just
370 catch all exceptions and return \"\" in the handler. However, this has
371 all sorts of undesirable consequences. For example, if the user
372 presses control-C at just the right moment then the 'UserInterrupt'
373 exception will be caught, and the program will continue running under
374 the belief that the file contains \"\". Similarly, if another thread
375 tries to kill the thread reading the file then the 'ThreadKilled'
376 exception will be ignored.
377
378 Instead, you should only catch exactly the exceptions that you really
379 want. In this case, this would likely be more specific than even
380 \"any IO exception\"; a permissions error would likely also want to be
381 handled differently. Instead, you would probably want something like:
382
383 > e <- tryJust (guard . isDoesNotExistError) (readFile f)
384 > let str = either (const "") id e
385
386 There are occassions when you really do need to catch any sort of
387 exception. However, in most cases this is just so you can do some
388 cleaning up; you aren't actually interested in the exception itself.
389 For example, if you open a file then you want to close it again,
390 whether processing the file executes normally or throws an exception.
391 However, in these cases you can use functions like 'bracket', 'finally'
392 and 'onException', which never actually pass you the exception, but
393 just call the cleanup functions at the appropriate points.
394
395 But sometimes you really do need to catch any exception, and actually
396 see what the exception is. One example is at the very top-level of a
397 program, you may wish to catch any exception, print it to a logfile or
398 the screen, and then exit gracefully. For these cases, you can use
399 'catch' (or one of the other exception-catching functions) with the
400 'SomeException' type.
401 -}
402