Update the Exception docs
[ghc-base.git] / Control / Exception.hs
1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  Control.Exception
6 -- Copyright   :  (c) The University of Glasgow 2001
7 -- License     :  BSD-style (see the file libraries/base/LICENSE)
8 --
9 -- Maintainer  :  libraries@haskell.org
10 -- Stability   :  experimental
11 -- Portability :  non-portable (extended exceptions)
12 --
13 -- This module provides support for raising and catching both built-in
14 -- and user-defined exceptions.
15 --
16 -- In addition to exceptions thrown by 'IO' operations, exceptions may
17 -- be thrown by pure code (imprecise exceptions) or by external events
18 -- (asynchronous exceptions), but may only be caught in the 'IO' monad.
19 -- For more details, see:
20 --
21 --  * /A semantics for imprecise exceptions/, by Simon Peyton Jones,
22 --    Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson,
23 --    in /PLDI'99/.
24 --
25 --  * /Asynchronous exceptions in Haskell/, by Simon Marlow, Simon Peyton
26 --    Jones, Andy Moran and John Reppy, in /PLDI'01/.
27 --
28 --  * /An Extensible Dynamically-Typed Hierarchy of Exceptions/,
29 --    by Simon Marlow, in /Haskell '06/.
30 --
31 -----------------------------------------------------------------------------
32
33 module Control.Exception (
34
35         -- * The Exception type
36 #ifdef __HUGS__
37         SomeException,
38 #else
39         SomeException(..),
40 #endif
41         Exception(..),          -- class
42         IOException,            -- instance Eq, Ord, Show, Typeable, Exception
43         ArithException(..),     -- instance Eq, Ord, Show, Typeable, Exception
44         ArrayException(..),     -- instance Eq, Ord, Show, Typeable, Exception
45         AssertionFailed(..),
46         AsyncException(..),     -- instance Eq, Ord, Show, Typeable, Exception
47
48 #if __GLASGOW_HASKELL__ || __HUGS__
49         NonTermination(..),
50         NestedAtomically(..),
51 #endif
52 #ifdef __NHC__
53         System.ExitCode(), -- instance Exception
54 #endif
55
56         BlockedOnDeadMVar(..),
57         BlockedIndefinitely(..),
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         -- |There are several functions for catching and examining
77         -- exceptions; all of them may only be used from within the
78         -- 'IO' monad.
79
80         -- ** The @catch@ functions
81         catch,
82         catches, Handler(..),
83         catchJust,
84
85         -- ** The @handle@ functions
86         handle,
87         handleJust,
88
89         -- ** The @try@ functions
90         try,
91         tryJust,
92
93         -- ** The @evaluate@ function
94         evaluate,
95
96         -- ** The @mapException@ function
97         mapException,
98
99         -- * Asynchronous Exceptions
100
101         -- $async
102
103         -- ** Asynchronous exception control
104
105         -- |The following two functions allow a thread to control delivery of
106         -- asynchronous exceptions during a critical region.
107
108         block,
109         unblock,
110         blocked,
111
112         -- *** Applying @block@ to an exception handler
113
114         -- $block_handler
115
116         -- *** Interruptible operations
117
118         -- $interruptible
119
120         -- * Assertions
121
122         assert,
123
124         -- * Utilities
125
126         bracket,
127         bracket_,
128         bracketOnError,
129
130         finally,
131         onException,
132
133         -- * Catching all exceptions
134
135         -- $catchall
136   ) where
137
138 import Control.Exception.Base
139
140 #ifdef __GLASGOW_HASKELL__
141 import GHC.Base
142 import GHC.IOBase
143 import Data.Maybe
144 #else
145 import Prelude hiding (catch)
146 #endif
147
148 #ifdef __NHC__
149 import System (ExitCode())
150 #endif
151
152 -- | You need this when using 'catches'.
153 data Handler a = forall e . Exception e => Handler (e -> IO a)
154
155 {- |
156 Sometimes you want to catch two different sorts of exception. You could
157 do something like
158
159 > f = expr `catch` \ (ex :: ArithException) -> handleArith ex
160 >          `catch` \ (ex :: IOException)    -> handleIO    ex
161
162 However, there are a couple of problems with this approach. The first is
163 that having two exception handlers is inefficient. However, the more
164 serious issue is that the second exception handler will catch exceptions
165 in the first, e.g. in the example above, if @handleArith@ throws an
166 @IOException@ then the second exception handler will catch it.
167
168 Instead, we provide a function 'catches', which would be used thus:
169
170 > f = expr `catches` [Handler (\ (ex :: ArithException) -> handleArith ex),
171 >                     Handler (\ (ex :: IOException)    -> handleIO    ex)]
172 -}
173 catches :: IO a -> [Handler a] -> IO a
174 catches io handlers = io `catch` catchesHandler handlers
175
176 catchesHandler :: [Handler a] -> SomeException -> IO a
177 catchesHandler handlers e = foldr tryHandler (throw e) handlers
178     where tryHandler (Handler handler) res
179               = case fromException e of
180                 Just e' -> handler e'
181                 Nothing -> res
182
183 -- -----------------------------------------------------------------------------
184 -- Asynchronous exceptions
185
186 {- $async
187
188  #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
189 external influences, and can be raised at any point during execution.
190 'StackOverflow' and 'HeapOverflow' are two examples of
191 system-generated asynchronous exceptions.
192
193 The primary source of asynchronous exceptions, however, is
194 'throwTo':
195
196 >  throwTo :: ThreadId -> Exception -> IO ()
197
198 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
199 running thread to raise an arbitrary exception in another thread.  The
200 exception is therefore asynchronous with respect to the target thread,
201 which could be doing anything at the time it receives the exception.
202 Great care should be taken with asynchronous exceptions; it is all too
203 easy to introduce race conditions by the over zealous use of
204 'throwTo'.
205 -}
206
207 {- $block_handler
208 There\'s an implied 'block' around every exception handler in a call
209 to one of the 'catch' family of functions.  This is because that is
210 what you want most of the time - it eliminates a common race condition
211 in starting an exception handler, because there may be no exception
212 handler on the stack to handle another exception if one arrives
213 immediately.  If asynchronous exceptions are blocked on entering the
214 handler, though, we have time to install a new exception handler
215 before being interrupted.  If this weren\'t the default, one would have
216 to write something like
217
218 >      block (
219 >           catch (unblock (...))
220 >                      (\e -> handler)
221 >      )
222
223 If you need to unblock asynchronous exceptions again in the exception
224 handler, just use 'unblock' as normal.
225
226 Note that 'try' and friends /do not/ have a similar default, because
227 there is no exception handler in this case.  If you want to use 'try'
228 in an asynchronous-exception-safe way, you will need to use
229 'block'.
230 -}
231
232 {- $interruptible
233
234 Some operations are /interruptible/, which means that they can receive
235 asynchronous exceptions even in the scope of a 'block'.  Any function
236 which may itself block is defined as interruptible; this includes
237 'Control.Concurrent.MVar.takeMVar'
238 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
239 and most operations which perform
240 some I\/O with the outside world.  The reason for having
241 interruptible operations is so that we can write things like
242
243 >      block (
244 >         a <- takeMVar m
245 >         catch (unblock (...))
246 >               (\e -> ...)
247 >      )
248
249 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
250 then this particular
251 combination could lead to deadlock, because the thread itself would be
252 blocked in a state where it can\'t receive any asynchronous exceptions.
253 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
254 safe in the knowledge that the thread can receive exceptions right up
255 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
256 Similar arguments apply for other interruptible operations like
257 'System.IO.openFile'.
258 -}
259
260 {- $catchall
261
262 It is possible to catch all exceptions, by using the type 'SomeException':
263
264 > catch f (\e -> ... (e :: SomeException) ...)
265
266 HOWEVER, this is normally not what you want to do!
267
268 For example, suppose you want to read a file, but if it doesn't exist
269 then continue as if it contained \"\". In the old exceptions library,
270 the easy thing to do was just to catch all exceptions and return \"\" in
271 the handler. However, this has all sorts of undesirable consequences.
272 For example, if the user presses control-C at just the right moment then
273 the 'UserInterrupt' exception will be caught, and the program will
274 continue running under the belief that the file contains \"\".
275 Similarly, if another thread tries to kill the thread reading the file
276 then the 'ThreadKilled' exception will be ignored.
277
278 Instead, you should only catch exactly the exceptions that you really
279 want. In this case, this would likely be more specific than even
280 \"any IO exception\"; a permissions error would likely also want to be
281 handled differently. Instead, you would probably want something like:
282
283 > catchJust (\e -> if isDoesNotExistErrorType (ioeGetErrorType e) then Just () else Nothing)
284 >           (readFile f)
285 >           (\_ -> return "")
286
287 There are occassions when you really do need to catch any sort of
288 exception. However, in most cases this is just so you can do some
289 cleaning up; you aren't actually interested in the exception itself.
290 For example, if you open a file then you want to close it again,
291 whether processing the file executes normally or throws an exception.
292 However, in these cases you can use functions like 'bracket', 'finally'
293 and 'onException', which never actually pass you the exception, but
294 just call the cleanup functions at the appropriate points.
295
296 But sometimes you really do need to catch any exception, and actually
297 see what the exception is. One example is at the very top-level of a
298 program, you may wish to catch any exception, print it to a logfile or
299 the screen, and then exit gracefully. For these cases, you can use
300 'catch' (or one of the other exception-catching functions) with the
301 'SomeException' type.
302 -}
303