Remove Hugs98 specific code
[packages/base.git] / Control / Exception / Base.hs
1 {-# LANGUAGE Trustworthy #-}
2 {-# LANGUAGE CPP, NoImplicitPrelude, MagicHash #-}
3 #ifdef __GLASGOW_HASKELL__
4 {-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-}
5 #endif
6
7 #include "Typeable.h"
8
9 -----------------------------------------------------------------------------
10 -- |
11 -- Module : Control.Exception.Base
12 -- Copyright : (c) The University of Glasgow 2001
13 -- License : BSD-style (see the file libraries/base/LICENSE)
14 --
15 -- Maintainer : libraries@haskell.org
16 -- Stability : experimental
17 -- Portability : non-portable (extended exceptions)
18 --
19 -- Extensible exceptions, except for multiple handlers.
20 --
21 -----------------------------------------------------------------------------
22
23 module Control.Exception.Base (
24
25 -- * The Exception type
26 SomeException(..),
27 Exception(..),
28 IOException,
29 ArithException(..),
30 ArrayException(..),
31 AssertionFailed(..),
32 SomeAsyncException(..), AsyncException(..),
33 asyncExceptionToException, asyncExceptionFromException,
34
35 #ifdef __GLASGOW_HASKELL__
36 NonTermination(..),
37 NestedAtomically(..),
38 #endif
39
40 BlockedIndefinitelyOnMVar(..),
41 BlockedIndefinitelyOnSTM(..),
42 Deadlock(..),
43 NoMethodError(..),
44 PatternMatchFail(..),
45 RecConError(..),
46 RecSelError(..),
47 RecUpdError(..),
48 ErrorCall(..),
49
50 -- * Throwing exceptions
51 throwIO,
52 throw,
53 ioError,
54 #ifdef __GLASGOW_HASKELL__
55 throwTo,
56 #endif
57
58 -- * Catching Exceptions
59
60 -- ** The @catch@ functions
61 catch,
62 catchJust,
63
64 -- ** The @handle@ functions
65 handle,
66 handleJust,
67
68 -- ** The @try@ functions
69 try,
70 tryJust,
71 onException,
72
73 -- ** The @evaluate@ function
74 evaluate,
75
76 -- ** The @mapException@ function
77 mapException,
78
79 -- * Asynchronous Exceptions
80
81 -- ** Asynchronous exception control
82 mask,
83 mask_,
84 uninterruptibleMask,
85 uninterruptibleMask_,
86 MaskingState(..),
87 getMaskingState,
88
89 -- * Assertions
90
91 assert,
92
93 -- * Utilities
94
95 bracket,
96 bracket_,
97 bracketOnError,
98
99 finally,
100
101 #ifdef __GLASGOW_HASKELL__
102 -- * Calls for GHC runtime
103 recSelError, recConError, irrefutPatError, runtimeError,
104 nonExhaustiveGuardsError, patError, noMethodBindingError,
105 absentError,
106 nonTermination, nestedAtomically,
107 #endif
108 ) where
109
110 #ifdef __GLASGOW_HASKELL__
111 import GHC.Base
112 import GHC.IO hiding (bracket,finally,onException)
113 import GHC.IO.Exception
114 import GHC.Exception
115 import GHC.Show
116 -- import GHC.Exception hiding ( Exception )
117 import GHC.Conc.Sync
118 #endif
119
120 import Data.Dynamic
121 import Data.Either
122 import Data.Maybe
123
124 -----------------------------------------------------------------------------
125 -- Catching exceptions
126
127 -- |This is the simplest of the exception-catching functions. It
128 -- takes a single argument, runs it, and if an exception is raised
129 -- the \"handler\" is executed, with the value of the exception passed as an
130 -- argument. Otherwise, the result is returned as normal. For example:
131 --
132 -- > catch (readFile f)
133 -- > (\e -> do let err = show (e :: IOException)
134 -- > hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)
135 -- > return "")
136 --
137 -- Note that we have to give a type signature to @e@, or the program
138 -- will not typecheck as the type is ambiguous. While it is possible
139 -- to catch exceptions of any type, see the section \"Catching all
140 -- exceptions\" (in "Control.Exception") for an explanation of the problems with doing so.
141 --
142 -- For catching exceptions in pure (non-'IO') expressions, see the
143 -- function 'evaluate'.
144 --
145 -- Note that due to Haskell\'s unspecified evaluation order, an
146 -- expression may throw one of several possible exceptions: consider
147 -- the expression @(error \"urk\") + (1 \`div\` 0)@. Does
148 -- the expression throw
149 -- @ErrorCall \"urk\"@, or @DivideByZero@?
150 --
151 -- The answer is \"it might throw either\"; the choice is
152 -- non-deterministic. If you are catching any type of exception then you
153 -- might catch either. If you are calling @catch@ with type
154 -- @IO Int -> (ArithException -> IO Int) -> IO Int@ then the handler may
155 -- get run with @DivideByZero@ as an argument, or an @ErrorCall \"urk\"@
156 -- exception may be propogated further up. If you call it again, you
157 -- might get a the opposite behaviour. This is ok, because 'catch' is an
158 -- 'IO' computation.
159 --
160 catch :: Exception e
161 => IO a -- ^ The computation to run
162 -> (e -> IO a) -- ^ Handler to invoke if an exception is raised
163 -> IO a
164 #if __GLASGOW_HASKELL__
165 catch = catchException
166 #endif
167
168 -- | The function 'catchJust' is like 'catch', but it takes an extra
169 -- argument which is an /exception predicate/, a function which
170 -- selects which type of exceptions we\'re interested in.
171 --
172 -- > catchJust (\e -> if isDoesNotExistErrorType (ioeGetErrorType e) then Just () else Nothing)
173 -- > (readFile f)
174 -- > (\_ -> do hPutStrLn stderr ("No such file: " ++ show f)
175 -- > return "")
176 --
177 -- Any other exceptions which are not matched by the predicate
178 -- are re-raised, and may be caught by an enclosing
179 -- 'catch', 'catchJust', etc.
180 catchJust
181 :: Exception e
182 => (e -> Maybe b) -- ^ Predicate to select exceptions
183 -> IO a -- ^ Computation to run
184 -> (b -> IO a) -- ^ Handler
185 -> IO a
186 catchJust p a handler = catch a handler'
187 where handler' e = case p e of
188 Nothing -> throwIO e
189 Just b -> handler b
190
191 -- | A version of 'catch' with the arguments swapped around; useful in
192 -- situations where the code for the handler is shorter. For example:
193 --
194 -- > do handle (\NonTermination -> exitWith (ExitFailure 1)) $
195 -- > ...
196 handle :: Exception e => (e -> IO a) -> IO a -> IO a
197 handle = flip catch
198
199 -- | A version of 'catchJust' with the arguments swapped around (see
200 -- 'handle').
201 handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a
202 handleJust p = flip (catchJust p)
203
204 -----------------------------------------------------------------------------
205 -- 'mapException'
206
207 -- | This function maps one exception into another as proposed in the
208 -- paper \"A semantics for imprecise exceptions\".
209
210 -- Notice that the usage of 'unsafePerformIO' is safe here.
211
212 mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a
213 mapException f v = unsafePerformIO (catch (evaluate v)
214 (\x -> throwIO (f x)))
215
216 -----------------------------------------------------------------------------
217 -- 'try' and variations.
218
219 -- | Similar to 'catch', but returns an 'Either' result which is
220 -- @('Right' a)@ if no exception of type @e@ was raised, or @('Left' ex)@
221 -- if an exception of type @e@ was raised and its value is @ex@.
222 -- If any other type of exception is raised than it will be propogated
223 -- up to the next enclosing exception handler.
224 --
225 -- > try a = catch (Right `liftM` a) (return . Left)
226
227 try :: Exception e => IO a -> IO (Either e a)
228 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
229
230 -- | A variant of 'try' that takes an exception predicate to select
231 -- which exceptions are caught (c.f. 'catchJust'). If the exception
232 -- does not match the predicate, it is re-thrown.
233 tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)
234 tryJust p a = do
235 r <- try a
236 case r of
237 Right v -> return (Right v)
238 Left e -> case p e of
239 Nothing -> throwIO e
240 Just b -> return (Left b)
241
242 -- | Like 'finally', but only performs the final action if there was an
243 -- exception raised by the computation.
244 onException :: IO a -> IO b -> IO a
245 onException io what = io `catch` \e -> do _ <- what
246 throwIO (e :: SomeException)
247
248 -----------------------------------------------------------------------------
249 -- Some Useful Functions
250
251 -- | When you want to acquire a resource, do some work with it, and
252 -- then release the resource, it is a good idea to use 'bracket',
253 -- because 'bracket' will install the necessary exception handler to
254 -- release the resource in the event that an exception is raised
255 -- during the computation. If an exception is raised, then 'bracket' will
256 -- re-raise the exception (after performing the release).
257 --
258 -- A common example is opening a file:
259 --
260 -- > bracket
261 -- > (openFile "filename" ReadMode)
262 -- > (hClose)
263 -- > (\fileHandle -> do { ... })
264 --
265 -- The arguments to 'bracket' are in this order so that we can partially apply
266 -- it, e.g.:
267 --
268 -- > withFile name mode = bracket (openFile name mode) hClose
269 --
270 bracket
271 :: IO a -- ^ computation to run first (\"acquire resource\")
272 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
273 -> (a -> IO c) -- ^ computation to run in-between
274 -> IO c -- returns the value from the in-between computation
275 bracket before after thing =
276 mask $ \restore -> do
277 a <- before
278 r <- restore (thing a) `onException` after a
279 _ <- after a
280 return r
281
282 -- | A specialised variant of 'bracket' with just a computation to run
283 -- afterward.
284 --
285 finally :: IO a -- ^ computation to run first
286 -> IO b -- ^ computation to run afterward (even if an exception
287 -- was raised)
288 -> IO a -- returns the value from the first computation
289 a `finally` sequel =
290 mask $ \restore -> do
291 r <- restore a `onException` sequel
292 _ <- sequel
293 return r
294
295 -- | A variant of 'bracket' where the return value from the first computation
296 -- is not required.
297 bracket_ :: IO a -> IO b -> IO c -> IO c
298 bracket_ before after thing = bracket before (const after) (const thing)
299
300 -- | Like 'bracket', but only performs the final action if there was an
301 -- exception raised by the in-between computation.
302 bracketOnError
303 :: IO a -- ^ computation to run first (\"acquire resource\")
304 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
305 -> (a -> IO c) -- ^ computation to run in-between
306 -> IO c -- returns the value from the in-between computation
307 bracketOnError before after thing =
308 mask $ \restore -> do
309 a <- before
310 restore (thing a) `onException` after a
311
312 #if !__GLASGOW_HASKELL__
313 assert :: Bool -> a -> a
314 assert True x = x
315 assert False _ = throw (AssertionFailed "")
316 #endif
317
318 -----
319
320 #if __GLASGOW_HASKELL__
321 -- |A pattern match failed. The @String@ gives information about the
322 -- source location of the pattern.
323 data PatternMatchFail = PatternMatchFail String
324 INSTANCE_TYPEABLE0(PatternMatchFail,patternMatchFailTc,"PatternMatchFail")
325
326 instance Show PatternMatchFail where
327 showsPrec _ (PatternMatchFail err) = showString err
328
329 instance Exception PatternMatchFail
330
331 -----
332
333 -- |A record selector was applied to a constructor without the
334 -- appropriate field. This can only happen with a datatype with
335 -- multiple constructors, where some fields are in one constructor
336 -- but not another. The @String@ gives information about the source
337 -- location of the record selector.
338 data RecSelError = RecSelError String
339 INSTANCE_TYPEABLE0(RecSelError,recSelErrorTc,"RecSelError")
340
341 instance Show RecSelError where
342 showsPrec _ (RecSelError err) = showString err
343
344 instance Exception RecSelError
345
346 -----
347
348 -- |An uninitialised record field was used. The @String@ gives
349 -- information about the source location where the record was
350 -- constructed.
351 data RecConError = RecConError String
352 INSTANCE_TYPEABLE0(RecConError,recConErrorTc,"RecConError")
353
354 instance Show RecConError where
355 showsPrec _ (RecConError err) = showString err
356
357 instance Exception RecConError
358
359 -----
360
361 -- |A record update was performed on a constructor without the
362 -- appropriate field. This can only happen with a datatype with
363 -- multiple constructors, where some fields are in one constructor
364 -- but not another. The @String@ gives information about the source
365 -- location of the record update.
366 data RecUpdError = RecUpdError String
367 INSTANCE_TYPEABLE0(RecUpdError,recUpdErrorTc,"RecUpdError")
368
369 instance Show RecUpdError where
370 showsPrec _ (RecUpdError err) = showString err
371
372 instance Exception RecUpdError
373
374 -----
375
376 -- |A class method without a definition (neither a default definition,
377 -- nor a definition in the appropriate instance) was called. The
378 -- @String@ gives information about which method it was.
379 data NoMethodError = NoMethodError String
380 INSTANCE_TYPEABLE0(NoMethodError,noMethodErrorTc,"NoMethodError")
381
382 instance Show NoMethodError where
383 showsPrec _ (NoMethodError err) = showString err
384
385 instance Exception NoMethodError
386
387 -----
388
389 -- |Thrown when the runtime system detects that the computation is
390 -- guaranteed not to terminate. Note that there is no guarantee that
391 -- the runtime system will notice whether any given computation is
392 -- guaranteed to terminate or not.
393 data NonTermination = NonTermination
394 INSTANCE_TYPEABLE0(NonTermination,nonTerminationTc,"NonTermination")
395
396 instance Show NonTermination where
397 showsPrec _ NonTermination = showString "<<loop>>"
398
399 instance Exception NonTermination
400
401 -----
402
403 -- |Thrown when the program attempts to call @atomically@, from the @stm@
404 -- package, inside another call to @atomically@.
405 data NestedAtomically = NestedAtomically
406 INSTANCE_TYPEABLE0(NestedAtomically,nestedAtomicallyTc,"NestedAtomically")
407
408 instance Show NestedAtomically where
409 showsPrec _ NestedAtomically = showString "Control.Concurrent.STM.atomically was nested"
410
411 instance Exception NestedAtomically
412
413 -----
414
415 #endif /* __GLASGOW_HASKELL__ */
416
417 #ifdef __GLASGOW_HASKELL__
418 recSelError, recConError, irrefutPatError, runtimeError,
419 nonExhaustiveGuardsError, patError, noMethodBindingError,
420 absentError
421 :: Addr# -> a -- All take a UTF8-encoded C string
422
423 recSelError s = throw (RecSelError ("No match in record selector "
424 ++ unpackCStringUtf8# s)) -- No location info unfortunately
425 runtimeError s = error (unpackCStringUtf8# s) -- No location info unfortunately
426 absentError s = error ("Oops! Entered absent arg " ++ unpackCStringUtf8# s)
427
428 nonExhaustiveGuardsError s = throw (PatternMatchFail (untangle s "Non-exhaustive guards in"))
429 irrefutPatError s = throw (PatternMatchFail (untangle s "Irrefutable pattern failed for pattern"))
430 recConError s = throw (RecConError (untangle s "Missing field in record construction"))
431 noMethodBindingError s = throw (NoMethodError (untangle s "No instance nor default method for class operation"))
432 patError s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))
433
434 -- GHC's RTS calls this
435 nonTermination :: SomeException
436 nonTermination = toException NonTermination
437
438 -- GHC's RTS calls this
439 nestedAtomically :: SomeException
440 nestedAtomically = toException NestedAtomically
441 #endif