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