Control.Exception doesn't need to export assertError
[ghc-base.git] / Control / Exception.hs
1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2
3 #include "Typeable.h"
4
5 -----------------------------------------------------------------------------
6 -- |
7 -- Module      :  Control.Exception
8 -- Copyright   :  (c) The University of Glasgow 2001
9 -- License     :  BSD-style (see the file libraries/base/LICENSE)
10 -- 
11 -- Maintainer  :  libraries@haskell.org
12 -- Stability   :  experimental
13 -- Portability :  non-portable (extended exceptions)
14 --
15 -- This module provides support for raising and catching both built-in
16 -- and user-defined exceptions.
17 --
18 -- In addition to exceptions thrown by 'IO' operations, exceptions may
19 -- be thrown by pure code (imprecise exceptions) or by external events
20 -- (asynchronous exceptions), but may only be caught in the 'IO' monad.
21 -- For more details, see:
22 --
23 --  * /A semantics for imprecise exceptions/, by Simon Peyton Jones,
24 --    Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson,
25 --    in /PLDI'99/.
26 --
27 --  * /Asynchronous exceptions in Haskell/, by Simon Marlow, Simon Peyton
28 --    Jones, Andy Moran and John Reppy, in /PLDI'01/.
29 --
30 -----------------------------------------------------------------------------
31
32 module Control.Exception (
33
34         -- * The Exception type
35         SomeException(..),
36         Exception(..),          -- instance Eq, Ord, Show, Typeable
37         IOException,            -- instance Eq, Ord, Show, Typeable
38         ArithException(..),     -- instance Eq, Ord, Show, Typeable
39         ArrayException(..),     -- instance Eq, Ord, Show, Typeable
40         AssertionFailed(..),
41         AsyncException(..),     -- instance Eq, Ord, Show, Typeable
42
43 #ifdef __GLASGOW_HASKELL__
44         NonTermination(..), nonTermination,
45         NestedAtomically(..), nestedAtomically,
46 #endif
47
48         BlockedOnDeadMVar(..),
49         BlockedIndefinitely(..),
50         Deadlock(..),
51         NoMethodError(..),
52         PatternMatchFail(..),
53         RecConError(..),
54         RecSelError(..),
55         RecUpdError(..),
56         ErrorCall(..),
57
58         -- * Throwing exceptions
59         throwIO,        -- :: Exception -> IO a
60         throw,          -- :: Exception -> a
61         ioError,        -- :: IOError -> IO a
62 #ifdef __GLASGOW_HASKELL__
63         throwTo,        -- :: ThreadId -> Exception -> a
64 #endif
65
66         -- * Catching Exceptions
67
68         -- |There are several functions for catching and examining
69         -- exceptions; all of them may only be used from within the
70         -- 'IO' monad.
71
72         -- ** The @catch@ functions
73         catch,     -- :: IO a -> (Exception -> IO a) -> IO a
74 #ifdef __GLASGOW_HASKELL__
75         catches, Handler(..),
76         catchJust, -- :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a
77 #endif
78
79         -- ** The @handle@ functions
80         handle,    -- :: (Exception -> IO a) -> IO a -> IO a
81         handleJust,-- :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
82
83         -- ** The @try@ functions
84         try,       -- :: IO a -> IO (Either Exception a)
85         tryJust,   -- :: (Exception -> Maybe b) -> a    -> IO (Either b a)
86         onException,
87
88         -- ** The @evaluate@ function
89         evaluate,  -- :: a -> IO a
90
91         -- ** The @mapException@ function
92         mapException,           -- :: (Exception -> Exception) -> a -> a
93
94         -- * Asynchronous Exceptions
95
96         -- $async
97
98         -- ** Asynchronous exception control
99
100         -- |The following two functions allow a thread to control delivery of
101         -- asynchronous exceptions during a critical region.
102
103         block,          -- :: IO a -> IO a
104         unblock,        -- :: IO a -> IO a
105         blocked,        -- :: IO Bool
106
107         -- *** Applying @block@ to an exception handler
108
109         -- $block_handler
110
111         -- *** Interruptible operations
112
113         -- $interruptible
114
115         -- * Assertions
116
117         assert,         -- :: Bool -> a -> a
118
119         -- * Utilities
120
121         bracket,        -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO ()
122         bracket_,       -- :: IO a -> IO b -> IO c -> IO ()
123         bracketOnError,
124
125         finally,        -- :: IO a -> IO b -> IO a
126
127 #ifdef __GLASGOW_HASKELL__
128         recSelError, recConError, irrefutPatError, runtimeError,
129         nonExhaustiveGuardsError, patError, noMethodBindingError,
130 #endif
131   ) where
132
133 #ifdef __GLASGOW_HASKELL__
134 import GHC.Base
135 import GHC.IOBase
136 import GHC.List
137 import GHC.Show
138 import GHC.IOBase as ExceptionBase
139 import GHC.Exception hiding ( Exception )
140 import GHC.Conc
141 #endif
142
143 #ifdef __HUGS__
144 import Hugs.Exception   as ExceptionBase
145 #endif
146
147 import Data.Dynamic
148 import Data.Either
149 import Data.Maybe
150
151 #ifdef __NHC__
152 import qualified System.IO.Error as H'98 (catch)
153 import System.IO.Error (ioError)
154 import IO              (bracket)
155 import DIOError         -- defn of IOError type
156 import System          (ExitCode())
157 import System.IO.Unsafe (unsafePerformIO)
158 import Unsafe.Coerce    (unsafeCoerce)
159
160 -- minimum needed for nhc98 to pretend it has Exceptions
161
162 {-
163 data Exception   = IOException    IOException
164                  | ArithException ArithException
165                  | ArrayException ArrayException
166                  | AsyncException AsyncException
167                  | ExitException  ExitCode
168                  deriving Show
169 -}
170 class ({-Typeable e,-} Show e) => Exception e where
171     toException   :: e -> SomeException
172     fromException :: SomeException -> Maybe e
173
174 data SomeException = forall e . Exception e => SomeException e
175
176 INSTANCE_TYPEABLE0(SomeException,someExceptionTc,"SomeException")
177
178 instance Show SomeException where
179     showsPrec p (SomeException e) = showsPrec p e
180 instance Exception SomeException where
181     toException se = se
182     fromException = Just
183
184 type IOException = IOError
185 instance Exception IOError where
186     toException                     = SomeException
187     fromException (SomeException e) = Just (unsafeCoerce e)
188
189 instance Exception ExitCode where
190     toException                     = SomeException
191     fromException (SomeException e) = Just (unsafeCoerce e)
192
193 data ArithException
194 data ArrayException
195 data AsyncException
196 data AssertionFailed
197 data PatternMatchFail
198 data NoMethodError
199 data Deadlock
200 data BlockedOnDeadMVar
201 data BlockedIndefinitely
202 data ErrorCall
203 data RecConError
204 data RecSelError
205 data RecUpdError
206 instance Show ArithException
207 instance Show ArrayException
208 instance Show AsyncException
209 instance Show AssertionFailed
210 instance Show PatternMatchFail
211 instance Show NoMethodError
212 instance Show Deadlock
213 instance Show BlockedOnDeadMVar
214 instance Show BlockedIndefinitely
215 instance Show ErrorCall
216 instance Show RecConError
217 instance Show RecSelError
218 instance Show RecUpdError
219
220 catch   :: Exception e
221         => IO a         -- ^ The computation to run
222         -> (e -> IO a)  -- ^ Handler to invoke if an exception is raised
223         -> IO a
224 catch io h = H'98.catch  io  (h . fromJust . fromException . toException)
225
226 throwIO  :: Exception e => e -> IO a
227 throwIO   = ioError . fromJust . fromException . toException
228
229 throw    :: Exception e => e -> a
230 throw     = unsafePerformIO . throwIO
231
232 evaluate :: a -> IO a
233 evaluate x = x `seq` return x
234
235 assert :: Bool -> a -> a
236 assert True  x = x
237 assert False _ = throw (toException (UserError "" "Assertion failed"))
238
239 #endif
240
241 #ifndef __GLASGOW_HASKELL__
242 -- Dummy definitions for implementations lacking asynchonous exceptions
243
244 block   :: IO a -> IO a
245 block    = id
246 unblock :: IO a -> IO a
247 unblock  = id
248 blocked :: IO Bool
249 blocked  = return False
250 #endif
251
252 -----------------------------------------------------------------------------
253 -- Catching exceptions
254
255 -- |This is the simplest of the exception-catching functions.  It
256 -- takes a single argument, runs it, and if an exception is raised
257 -- the \"handler\" is executed, with the value of the exception passed as an
258 -- argument.  Otherwise, the result is returned as normal.  For example:
259 --
260 -- >   catch (openFile f ReadMode) 
261 -- >       (\e -> hPutStr stderr ("Couldn't open "++f++": " ++ show e))
262 --
263 -- For catching exceptions in pure (non-'IO') expressions, see the
264 -- function 'evaluate'.
265 --
266 -- Note that due to Haskell\'s unspecified evaluation order, an
267 -- expression may return one of several possible exceptions: consider
268 -- the expression @error \"urk\" + 1 \`div\` 0@.  Does
269 -- 'catch' execute the handler passing
270 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
271 --
272 -- The answer is \"either\": 'catch' makes a
273 -- non-deterministic choice about which exception to catch.  If you
274 -- call it again, you might get a different exception back.  This is
275 -- ok, because 'catch' is an 'IO' computation.
276 --
277 -- Note that 'catch' catches all types of exceptions, and is generally
278 -- used for \"cleaning up\" before passing on the exception using
279 -- 'throwIO'.  It is not good practice to discard the exception and
280 -- continue, without first checking the type of the exception (it
281 -- might be a 'ThreadKilled', for example).  In this case it is usually better
282 -- to use 'catchJust' and select the kinds of exceptions to catch.
283 --
284 -- Also note that the "Prelude" also exports a function called
285 -- 'Prelude.catch' with a similar type to 'Control.Exception.catch',
286 -- except that the "Prelude" version only catches the IO and user
287 -- families of exceptions (as required by Haskell 98).  
288 --
289 -- We recommend either hiding the "Prelude" version of 'Prelude.catch'
290 -- when importing "Control.Exception": 
291 --
292 -- > import Prelude hiding (catch)
293 --
294 -- or importing "Control.Exception" qualified, to avoid name-clashes:
295 --
296 -- > import qualified Control.Exception as C
297 --
298 -- and then using @C.catch@
299 --
300 #ifndef __NHC__
301 catch   :: Exception e
302         => IO a         -- ^ The computation to run
303         -> (e -> IO a)  -- ^ Handler to invoke if an exception is raised
304         -> IO a
305 catch = ExceptionBase.catchException
306 #endif
307
308 catches :: IO a -> [Handler a] -> IO a
309 catches io handlers = io `catch` catchesHandler handlers
310
311 catchesHandler :: [Handler a] -> SomeException -> IO a
312 catchesHandler handlers e = foldr tryHandler (throw e) handlers
313     where tryHandler (Handler handler) res
314               = case fromException e of
315                 Just e' -> handler e'
316                 Nothing -> res
317
318 data Handler a = forall e . Exception e => Handler (e -> IO a)
319 -- | The function 'catchJust' is like 'catch', but it takes an extra
320 -- argument which is an /exception predicate/, a function which
321 -- selects which type of exceptions we\'re interested in.
322 --
323 -- >   result <- catchJust errorCalls thing_to_try handler
324 --
325 -- Any other exceptions which are not matched by the predicate
326 -- are re-raised, and may be caught by an enclosing
327 -- 'catch' or 'catchJust'.
328 catchJust
329         :: Exception e
330         => (e -> Maybe b)         -- ^ Predicate to select exceptions
331         -> IO a                   -- ^ Computation to run
332         -> (b -> IO a)            -- ^ Handler
333         -> IO a
334 catchJust p a handler = catch a handler'
335   where handler' e = case p e of 
336                         Nothing -> throw e
337                         Just b  -> handler b
338
339 -- | A version of 'catch' with the arguments swapped around; useful in
340 -- situations where the code for the handler is shorter.  For example:
341 --
342 -- >   do handle (\e -> exitWith (ExitFailure 1)) $
343 -- >      ...
344 handle     :: Exception e => (e -> IO a) -> IO a -> IO a
345 handle     =  flip catch
346
347 -- | A version of 'catchJust' with the arguments swapped around (see
348 -- 'handle').
349 handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a
350 handleJust p =  flip (catchJust p)
351
352 -----------------------------------------------------------------------------
353 -- 'mapException'
354
355 -- | This function maps one exception into another as proposed in the
356 -- paper \"A semantics for imprecise exceptions\".
357
358 -- Notice that the usage of 'unsafePerformIO' is safe here.
359
360 mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a
361 mapException f v = unsafePerformIO (catch (evaluate v)
362                                           (\x -> throw (f x)))
363
364 -----------------------------------------------------------------------------
365 -- 'try' and variations.
366
367 -- | Similar to 'catch', but returns an 'Either' result which is
368 -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an
369 -- exception was raised and its value is @e@.
370 --
371 -- >  try a = catch (Right `liftM` a) (return . Left)
372 --
373 -- Note: as with 'catch', it is only polite to use this variant if you intend
374 -- to re-throw the exception after performing whatever cleanup is needed.
375 -- Otherwise, 'tryJust' is generally considered to be better.
376 --
377 -- Also note that "System.IO.Error" also exports a function called
378 -- 'System.IO.Error.try' with a similar type to 'Control.Exception.try',
379 -- except that it catches only the IO and user families of exceptions
380 -- (as required by the Haskell 98 @IO@ module).
381
382 try :: Exception e => IO a -> IO (Either e a)
383 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
384
385 -- | A variant of 'try' that takes an exception predicate to select
386 -- which exceptions are caught (c.f. 'catchJust').  If the exception
387 -- does not match the predicate, it is re-thrown.
388 tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)
389 tryJust p a = do
390   r <- try a
391   case r of
392         Right v -> return (Right v)
393         Left  e -> case p e of
394                         Nothing -> throw e
395                         Just b  -> return (Left b)
396
397 onException :: IO a -> IO b -> IO a
398 onException io what = io `catch` \e -> do what
399                                           throw (e :: SomeException)
400
401 -----------------------------------------------------------------------------
402 -- Some Useful Functions
403
404 -- | When you want to acquire a resource, do some work with it, and
405 -- then release the resource, it is a good idea to use 'bracket',
406 -- because 'bracket' will install the necessary exception handler to
407 -- release the resource in the event that an exception is raised
408 -- during the computation.  If an exception is raised, then 'bracket' will 
409 -- re-raise the exception (after performing the release).
410 --
411 -- A common example is opening a file:
412 --
413 -- > bracket
414 -- >   (openFile "filename" ReadMode)
415 -- >   (hClose)
416 -- >   (\handle -> do { ... })
417 --
418 -- The arguments to 'bracket' are in this order so that we can partially apply 
419 -- it, e.g.:
420 --
421 -- > withFile name mode = bracket (openFile name mode) hClose
422 --
423 #ifndef __NHC__
424 bracket 
425         :: IO a         -- ^ computation to run first (\"acquire resource\")
426         -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
427         -> (a -> IO c)  -- ^ computation to run in-between
428         -> IO c         -- returns the value from the in-between computation
429 bracket before after thing =
430   block (do
431     a <- before 
432     r <- unblock (thing a) `onException` after a
433     after a
434     return r
435  )
436 #endif
437
438 -- | A specialised variant of 'bracket' with just a computation to run
439 -- afterward.
440 -- 
441 finally :: IO a         -- ^ computation to run first
442         -> IO b         -- ^ computation to run afterward (even if an exception 
443                         -- was raised)
444         -> IO a         -- returns the value from the first computation
445 a `finally` sequel =
446   block (do
447     r <- unblock a `onException` sequel
448     sequel
449     return r
450   )
451
452 -- | A variant of 'bracket' where the return value from the first computation
453 -- is not required.
454 bracket_ :: IO a -> IO b -> IO c -> IO c
455 bracket_ before after thing = bracket before (const after) (const thing)
456
457 -- | Like bracket, but only performs the final action if there was an 
458 -- exception raised by the in-between computation.
459 bracketOnError
460         :: IO a         -- ^ computation to run first (\"acquire resource\")
461         -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
462         -> (a -> IO c)  -- ^ computation to run in-between
463         -> IO c         -- returns the value from the in-between computation
464 bracketOnError before after thing =
465   block (do
466     a <- before 
467     unblock (thing a) `onException` after a
468   )
469
470 -- -----------------------------------------------------------------------------
471 -- Asynchronous exceptions
472
473 {- $async
474
475  #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
476 external influences, and can be raised at any point during execution.
477 'StackOverflow' and 'HeapOverflow' are two examples of
478 system-generated asynchronous exceptions.
479
480 The primary source of asynchronous exceptions, however, is
481 'throwTo':
482
483 >  throwTo :: ThreadId -> Exception -> IO ()
484
485 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
486 running thread to raise an arbitrary exception in another thread.  The
487 exception is therefore asynchronous with respect to the target thread,
488 which could be doing anything at the time it receives the exception.
489 Great care should be taken with asynchronous exceptions; it is all too
490 easy to introduce race conditions by the over zealous use of
491 'throwTo'.
492 -}
493
494 {- $block_handler
495 There\'s an implied 'block' around every exception handler in a call
496 to one of the 'catch' family of functions.  This is because that is
497 what you want most of the time - it eliminates a common race condition
498 in starting an exception handler, because there may be no exception
499 handler on the stack to handle another exception if one arrives
500 immediately.  If asynchronous exceptions are blocked on entering the
501 handler, though, we have time to install a new exception handler
502 before being interrupted.  If this weren\'t the default, one would have
503 to write something like
504
505 >      block (
506 >           catch (unblock (...))
507 >                      (\e -> handler)
508 >      )
509
510 If you need to unblock asynchronous exceptions again in the exception
511 handler, just use 'unblock' as normal.
512
513 Note that 'try' and friends /do not/ have a similar default, because
514 there is no exception handler in this case.  If you want to use 'try'
515 in an asynchronous-exception-safe way, you will need to use
516 'block'.
517 -}
518
519 {- $interruptible
520
521 Some operations are /interruptible/, which means that they can receive
522 asynchronous exceptions even in the scope of a 'block'.  Any function
523 which may itself block is defined as interruptible; this includes
524 'Control.Concurrent.MVar.takeMVar'
525 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
526 and most operations which perform
527 some I\/O with the outside world.  The reason for having
528 interruptible operations is so that we can write things like
529
530 >      block (
531 >         a <- takeMVar m
532 >         catch (unblock (...))
533 >               (\e -> ...)
534 >      )
535
536 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
537 then this particular
538 combination could lead to deadlock, because the thread itself would be
539 blocked in a state where it can\'t receive any asynchronous exceptions.
540 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
541 safe in the knowledge that the thread can receive exceptions right up
542 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
543 Similar arguments apply for other interruptible operations like
544 'System.IO.openFile'.
545 -}
546
547 #if !(__GLASGOW_HASKELL__ || __NHC__)
548 assert :: Bool -> a -> a
549 assert True x = x
550 assert False _ = throw (AssertionFailed "")
551 #endif
552
553 #ifndef __NHC__
554 recSelError, recConError, irrefutPatError, runtimeError,
555              nonExhaustiveGuardsError, patError, noMethodBindingError
556         :: Addr# -> a   -- All take a UTF8-encoded C string
557
558 recSelError              s = throw (RecSelError (unpackCStringUtf8# s)) -- No location info unfortunately
559 runtimeError             s = error (unpackCStringUtf8# s)               -- No location info unfortunately
560
561 nonExhaustiveGuardsError s = throw (PatternMatchFail (untangle s "Non-exhaustive guards in"))
562 irrefutPatError          s = throw (PatternMatchFail (untangle s "Irrefutable pattern failed for pattern"))
563 recConError              s = throw (RecConError      (untangle s "Missing field in record construction"))
564 noMethodBindingError     s = throw (NoMethodError    (untangle s "No instance nor default method for class operation"))
565 patError                 s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))
566
567 -----
568
569 data PatternMatchFail = PatternMatchFail String
570 INSTANCE_TYPEABLE0(PatternMatchFail,patternMatchFailTc,"PatternMatchFail")
571
572 instance Exception PatternMatchFail
573
574 instance Show PatternMatchFail where
575     showsPrec _ (PatternMatchFail err) = showString err
576
577 -----
578
579 data RecSelError = RecSelError String
580 INSTANCE_TYPEABLE0(RecSelError,recSelErrorTc,"RecSelError")
581
582 instance Exception RecSelError
583
584 instance Show RecSelError where
585     showsPrec _ (RecSelError err) = showString err
586
587 -----
588
589 data RecConError = RecConError String
590 INSTANCE_TYPEABLE0(RecConError,recConErrorTc,"RecConError")
591
592 instance Exception RecConError
593
594 instance Show RecConError where
595     showsPrec _ (RecConError err) = showString err
596
597 -----
598
599 data RecUpdError = RecUpdError String
600 INSTANCE_TYPEABLE0(RecUpdError,recUpdErrorTc,"RecUpdError")
601
602 instance Exception RecUpdError
603
604 instance Show RecUpdError where
605     showsPrec _ (RecUpdError err) = showString err
606
607 -----
608
609 data NoMethodError = NoMethodError String
610 INSTANCE_TYPEABLE0(NoMethodError,noMethodErrorTc,"NoMethodError")
611
612 instance Exception NoMethodError
613
614 instance Show NoMethodError where
615     showsPrec _ (NoMethodError err) = showString err
616
617 -----
618
619 data NonTermination = NonTermination
620 INSTANCE_TYPEABLE0(NonTermination,nonTerminationTc,"NonTermination")
621
622 instance Exception NonTermination
623
624 instance Show NonTermination where
625     showsPrec _ NonTermination = showString "<<loop>>"
626
627 -- GHC's RTS calls this
628 nonTermination :: SomeException
629 nonTermination = toException NonTermination
630
631 -----
632
633 data NestedAtomically = NestedAtomically
634 INSTANCE_TYPEABLE0(NestedAtomically,nestedAtomicallyTc,"NestedAtomically")
635
636 instance Exception NestedAtomically
637
638 instance Show NestedAtomically where
639     showsPrec _ NestedAtomically = showString "Control.Concurrent.STM.atomically was nested"
640
641 -- GHC's RTS calls this
642 nestedAtomically :: SomeException
643 nestedAtomically = toException NestedAtomically
644
645 -----
646
647 instance Exception Dynamic
648
649 #endif
650