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