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