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