1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2 {-# OPTIONS_GHC -fno-warn-orphans #-}
6 -----------------------------------------------------------------------------
8 -- Module : Control.Exception.Base
9 -- Copyright : (c) The University of Glasgow 2001
10 -- License : BSD-style (see the file libraries/base/LICENSE)
12 -- Maintainer : libraries@haskell.org
13 -- Stability : experimental
14 -- Portability : non-portable (extended exceptions)
16 -- Extensible exceptions, except for multiple handlers.
18 -----------------------------------------------------------------------------
20 module Control.Exception.Base (
22 -- * The Exception type
35 #if __GLASGOW_HASKELL__ || __HUGS__
40 BlockedOnDeadMVar(..),
41 BlockedIndefinitely(..),
50 -- * Throwing exceptions
54 #ifdef __GLASGOW_HASKELL__
58 -- * Catching Exceptions
60 -- ** The @catch@ functions
64 -- ** The @handle@ functions
68 -- ** The @try@ functions
73 -- ** The @evaluate@ function
76 -- ** The @mapException@ function
79 -- * Asynchronous Exceptions
81 -- ** Asynchronous exception control
99 #ifdef __GLASGOW_HASKELL__
100 -- * Calls for GHC runtime
101 recSelError, recConError, irrefutPatError, runtimeError,
102 nonExhaustiveGuardsError, patError, noMethodBindingError,
103 nonTermination, nestedAtomically,
107 #ifdef __GLASGOW_HASKELL__
112 import GHC.Exception hiding ( Exception )
117 import Prelude hiding (catch)
118 import Hugs.Prelude (ExitCode(..))
119 import Hugs.IOExts (unsafePerformIO)
120 import Hugs.Exception (SomeException(DynamicException, IOException,
121 ArithException, ArrayException, ExitException),
122 evaluate, IOException, ArithException, ArrayException)
123 import qualified Hugs.Exception
131 import qualified System.IO.Error as H'98 (catch)
132 import System.IO.Error (ioError)
134 import DIOError -- defn of IOError type
135 import System (ExitCode())
136 import System.IO.Unsafe (unsafePerformIO)
137 import Unsafe.Coerce (unsafeCoerce)
139 -- minimum needed for nhc98 to pretend it has Exceptions
142 data Exception = IOException IOException
143 | ArithException ArithException
144 | ArrayException ArrayException
145 | AsyncException AsyncException
146 | ExitException ExitCode
149 class ({-Typeable e,-} Show e) => Exception e where
150 toException :: e -> SomeException
151 fromException :: SomeException -> Maybe e
153 data SomeException = forall e . Exception e => SomeException e
155 INSTANCE_TYPEABLE0(SomeException,someExceptionTc,"SomeException")
157 instance Show SomeException where
158 showsPrec p (SomeException e) = showsPrec p e
159 instance Exception SomeException where
163 type IOException = IOError
164 instance Exception IOError where
165 toException = SomeException
166 fromException (SomeException e) = Just (unsafeCoerce e)
168 instance Exception ExitCode where
169 toException = SomeException
170 fromException (SomeException e) = Just (unsafeCoerce e)
176 data PatternMatchFail
179 data BlockedOnDeadMVar
180 data BlockedIndefinitely
185 instance Show ArithException
186 instance Show ArrayException
187 instance Show AsyncException
188 instance Show AssertionFailed
189 instance Show PatternMatchFail
190 instance Show NoMethodError
191 instance Show Deadlock
192 instance Show BlockedOnDeadMVar
193 instance Show BlockedIndefinitely
194 instance Show ErrorCall
195 instance Show RecConError
196 instance Show RecSelError
197 instance Show RecUpdError
200 => IO a -- ^ The computation to run
201 -> (e -> IO a) -- ^ Handler to invoke if an exception is raised
203 catch io h = H'98.catch io (h . fromJust . fromException . toException)
205 throwIO :: Exception e => e -> IO a
206 throwIO = ioError . fromJust . fromException . toException
208 throw :: Exception e => e -> a
209 throw = unsafePerformIO . throwIO
211 evaluate :: a -> IO a
212 evaluate x = x `seq` return x
214 assert :: Bool -> a -> a
216 assert False _ = throw (toException (UserError "" "Assertion failed"))
221 class (Typeable e, Show e) => Exception e where
222 toException :: e -> SomeException
223 fromException :: SomeException -> Maybe e
225 toException e = DynamicException (toDyn e) (flip showsPrec e)
226 fromException (DynamicException dyn _) = fromDynamic dyn
227 fromException _ = Nothing
229 INSTANCE_TYPEABLE0(SomeException,someExceptionTc,"SomeException")
230 INSTANCE_TYPEABLE0(IOException,iOExceptionTc,"IOException")
231 INSTANCE_TYPEABLE0(ArithException,arithExceptionTc,"ArithException")
232 INSTANCE_TYPEABLE0(ArrayException,arrayExceptionTc,"ArrayException")
233 INSTANCE_TYPEABLE0(ExitCode,exitCodeTc,"ExitCode")
234 INSTANCE_TYPEABLE0(ErrorCall,errorCallTc,"ErrorCall")
235 INSTANCE_TYPEABLE0(AssertionFailed,assertionFailedTc,"AssertionFailed")
236 INSTANCE_TYPEABLE0(AsyncException,asyncExceptionTc,"AsyncException")
237 INSTANCE_TYPEABLE0(BlockedOnDeadMVar,blockedOnDeadMVarTc,"BlockedOnDeadMVar")
238 INSTANCE_TYPEABLE0(BlockedIndefinitely,blockedIndefinitelyTc,"BlockedIndefinitely")
239 INSTANCE_TYPEABLE0(Deadlock,deadlockTc,"Deadlock")
241 instance Exception SomeException where
245 instance Exception IOException where
246 toException = IOException
247 fromException (IOException e) = Just e
248 fromException _ = Nothing
250 instance Exception ArrayException where
251 toException = ArrayException
252 fromException (ArrayException e) = Just e
253 fromException _ = Nothing
255 instance Exception ArithException where
256 toException = ArithException
257 fromException (ArithException e) = Just e
258 fromException _ = Nothing
260 instance Exception ExitCode where
261 toException = ExitException
262 fromException (ExitException e) = Just e
263 fromException _ = Nothing
265 data ErrorCall = ErrorCall String
267 instance Show ErrorCall where
268 showsPrec _ (ErrorCall err) = showString err
270 instance Exception ErrorCall where
271 toException (ErrorCall s) = Hugs.Exception.ErrorCall s
272 fromException (Hugs.Exception.ErrorCall s) = Just (ErrorCall s)
273 fromException _ = Nothing
275 data BlockedOnDeadMVar = BlockedOnDeadMVar
276 data BlockedIndefinitely = BlockedIndefinitely
277 data Deadlock = Deadlock
278 data AssertionFailed = AssertionFailed String
286 instance Show BlockedOnDeadMVar where
287 showsPrec _ BlockedOnDeadMVar = showString "thread blocked indefinitely"
289 instance Show BlockedIndefinitely where
290 showsPrec _ BlockedIndefinitely = showString "thread blocked indefinitely"
292 instance Show Deadlock where
293 showsPrec _ Deadlock = showString "<<deadlock>>"
295 instance Show AssertionFailed where
296 showsPrec _ (AssertionFailed err) = showString err
298 instance Show AsyncException where
299 showsPrec _ StackOverflow = showString "stack overflow"
300 showsPrec _ HeapOverflow = showString "heap overflow"
301 showsPrec _ ThreadKilled = showString "thread killed"
302 showsPrec _ UserInterrupt = showString "user interrupt"
304 instance Exception BlockedOnDeadMVar
305 instance Exception BlockedIndefinitely
306 instance Exception Deadlock
307 instance Exception AssertionFailed
308 instance Exception AsyncException
310 throw :: Exception e => e -> a
311 throw e = Hugs.Exception.throw (toException e)
313 throwIO :: Exception e => e -> IO a
314 throwIO e = Hugs.Exception.throwIO (toException e)
317 #ifndef __GLASGOW_HASKELL__
318 -- Dummy definitions for implementations lacking asynchonous exceptions
320 block :: IO a -> IO a
322 unblock :: IO a -> IO a
325 blocked = return False
328 -----------------------------------------------------------------------------
329 -- Catching exceptions
331 -- |This is the simplest of the exception-catching functions. It
332 -- takes a single argument, runs it, and if an exception is raised
333 -- the \"handler\" is executed, with the value of the exception passed as an
334 -- argument. Otherwise, the result is returned as normal. For example:
336 -- > catch (openFile f ReadMode)
337 -- > (\e -> hPutStr stderr ("Couldn't open "++f++": " ++ show e))
339 -- For catching exceptions in pure (non-'IO') expressions, see the
340 -- function 'evaluate'.
342 -- Note that due to Haskell\'s unspecified evaluation order, an
343 -- expression may return one of several possible exceptions: consider
344 -- the expression @error \"urk\" + 1 \`div\` 0@. Does
345 -- 'catch' execute the handler passing
346 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
348 -- The answer is \"either\": 'catch' makes a
349 -- non-deterministic choice about which exception to catch. If you
350 -- call it again, you might get a different exception back. This is
351 -- ok, because 'catch' is an 'IO' computation.
353 -- Note that 'catch' catches all types of exceptions, and is generally
354 -- used for \"cleaning up\" before passing on the exception using
355 -- 'throwIO'. It is not good practice to discard the exception and
356 -- continue, without first checking the type of the exception (it
357 -- might be a 'ThreadKilled', for example). In this case it is usually better
358 -- to use 'catchJust' and select the kinds of exceptions to catch.
360 -- Also note that the "Prelude" also exports a function called
361 -- 'Prelude.catch' with a similar type to 'Control.Exception.catch',
362 -- except that the "Prelude" version only catches the IO and user
363 -- families of exceptions (as required by Haskell 98).
365 -- We recommend either hiding the "Prelude" version of 'Prelude.catch'
366 -- when importing "Control.Exception":
368 -- > import Prelude hiding (catch)
370 -- or importing "Control.Exception" qualified, to avoid name-clashes:
372 -- > import qualified Control.Exception as C
374 -- and then using @C.catch@
378 => IO a -- ^ The computation to run
379 -> (e -> IO a) -- ^ Handler to invoke if an exception is raised
381 #if __GLASGOW_HASKELL__
382 catch = GHC.IOBase.catchException
384 catch m h = Hugs.Exception.catchException m h'
385 where h' e = case fromException e of
391 -- | The function 'catchJust' is like 'catch', but it takes an extra
392 -- argument which is an /exception predicate/, a function which
393 -- selects which type of exceptions we\'re interested in.
395 -- > result <- catchJust errorCalls thing_to_try handler
397 -- Any other exceptions which are not matched by the predicate
398 -- are re-raised, and may be caught by an enclosing
399 -- 'catch' or 'catchJust'.
402 => (e -> Maybe b) -- ^ Predicate to select exceptions
403 -> IO a -- ^ Computation to run
404 -> (b -> IO a) -- ^ Handler
406 catchJust p a handler = catch a handler'
407 where handler' e = case p e of
411 -- | A version of 'catch' with the arguments swapped around; useful in
412 -- situations where the code for the handler is shorter. For example:
414 -- > do handle (\e -> exitWith (ExitFailure 1)) $
416 handle :: Exception e => (e -> IO a) -> IO a -> IO a
419 -- | A version of 'catchJust' with the arguments swapped around (see
421 handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a
422 handleJust p = flip (catchJust p)
424 -----------------------------------------------------------------------------
427 -- | This function maps one exception into another as proposed in the
428 -- paper \"A semantics for imprecise exceptions\".
430 -- Notice that the usage of 'unsafePerformIO' is safe here.
432 mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a
433 mapException f v = unsafePerformIO (catch (evaluate v)
436 -----------------------------------------------------------------------------
437 -- 'try' and variations.
439 -- | Similar to 'catch', but returns an 'Either' result which is
440 -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an
441 -- exception was raised and its value is @e@.
443 -- > try a = catch (Right `liftM` a) (return . Left)
445 -- Note: as with 'catch', it is only polite to use this variant if you intend
446 -- to re-throw the exception after performing whatever cleanup is needed.
447 -- Otherwise, 'tryJust' is generally considered to be better.
449 -- Also note that "System.IO.Error" also exports a function called
450 -- 'System.IO.Error.try' with a similar type to 'Control.Exception.try',
451 -- except that it catches only the IO and user families of exceptions
452 -- (as required by the Haskell 98 @IO@ module).
454 try :: Exception e => IO a -> IO (Either e a)
455 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
457 -- | A variant of 'try' that takes an exception predicate to select
458 -- which exceptions are caught (c.f. 'catchJust'). If the exception
459 -- does not match the predicate, it is re-thrown.
460 tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)
464 Right v -> return (Right v)
465 Left e -> case p e of
467 Just b -> return (Left b)
469 onException :: IO a -> IO b -> IO a
470 onException io what = io `catch` \e -> do what
471 throw (e :: SomeException)
473 -----------------------------------------------------------------------------
474 -- Some Useful Functions
476 -- | When you want to acquire a resource, do some work with it, and
477 -- then release the resource, it is a good idea to use 'bracket',
478 -- because 'bracket' will install the necessary exception handler to
479 -- release the resource in the event that an exception is raised
480 -- during the computation. If an exception is raised, then 'bracket' will
481 -- re-raise the exception (after performing the release).
483 -- A common example is opening a file:
486 -- > (openFile "filename" ReadMode)
488 -- > (\handle -> do { ... })
490 -- The arguments to 'bracket' are in this order so that we can partially apply
493 -- > withFile name mode = bracket (openFile name mode) hClose
497 :: IO a -- ^ computation to run first (\"acquire resource\")
498 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
499 -> (a -> IO c) -- ^ computation to run in-between
500 -> IO c -- returns the value from the in-between computation
501 bracket before after thing =
504 r <- unblock (thing a) `onException` after a
510 -- | A specialised variant of 'bracket' with just a computation to run
513 finally :: IO a -- ^ computation to run first
514 -> IO b -- ^ computation to run afterward (even if an exception
516 -> IO a -- returns the value from the first computation
519 r <- unblock a `onException` sequel
524 -- | A variant of 'bracket' where the return value from the first computation
526 bracket_ :: IO a -> IO b -> IO c -> IO c
527 bracket_ before after thing = bracket before (const after) (const thing)
529 -- | Like bracket, but only performs the final action if there was an
530 -- exception raised by the in-between computation.
532 :: IO a -- ^ computation to run first (\"acquire resource\")
533 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
534 -> (a -> IO c) -- ^ computation to run in-between
535 -> IO c -- returns the value from the in-between computation
536 bracketOnError before after thing =
539 unblock (thing a) `onException` after a
542 #if !(__GLASGOW_HASKELL__ || __NHC__)
543 assert :: Bool -> a -> a
545 assert False _ = throw (AssertionFailed "")
550 #if __GLASGOW_HASKELL__ || __HUGS__
551 data PatternMatchFail = PatternMatchFail String
552 INSTANCE_TYPEABLE0(PatternMatchFail,patternMatchFailTc,"PatternMatchFail")
554 instance Show PatternMatchFail where
555 showsPrec _ (PatternMatchFail err) = showString err
558 instance Exception PatternMatchFail where
559 toException (PatternMatchFail err) = Hugs.Exception.PatternMatchFail err
560 fromException (Hugs.Exception.PatternMatchFail err) = Just (PatternMatchFail err)
561 fromException _ = Nothing
563 instance Exception PatternMatchFail
568 data RecSelError = RecSelError String
569 INSTANCE_TYPEABLE0(RecSelError,recSelErrorTc,"RecSelError")
571 instance Show RecSelError where
572 showsPrec _ (RecSelError err) = showString err
575 instance Exception RecSelError where
576 toException (RecSelError err) = Hugs.Exception.RecSelError err
577 fromException (Hugs.Exception.RecSelError err) = Just (RecSelError err)
578 fromException _ = Nothing
580 instance Exception RecSelError
585 data RecConError = RecConError String
586 INSTANCE_TYPEABLE0(RecConError,recConErrorTc,"RecConError")
588 instance Show RecConError where
589 showsPrec _ (RecConError err) = showString err
592 instance Exception RecConError where
593 toException (RecConError err) = Hugs.Exception.RecConError err
594 fromException (Hugs.Exception.RecConError err) = Just (RecConError err)
595 fromException _ = Nothing
597 instance Exception RecConError
602 data RecUpdError = RecUpdError String
603 INSTANCE_TYPEABLE0(RecUpdError,recUpdErrorTc,"RecUpdError")
605 instance Show RecUpdError where
606 showsPrec _ (RecUpdError err) = showString err
609 instance Exception RecUpdError where
610 toException (RecUpdError err) = Hugs.Exception.RecUpdError err
611 fromException (Hugs.Exception.RecUpdError err) = Just (RecUpdError err)
612 fromException _ = Nothing
614 instance Exception RecUpdError
619 data NoMethodError = NoMethodError String
620 INSTANCE_TYPEABLE0(NoMethodError,noMethodErrorTc,"NoMethodError")
622 instance Show NoMethodError where
623 showsPrec _ (NoMethodError err) = showString err
626 instance Exception NoMethodError where
627 toException (NoMethodError err) = Hugs.Exception.NoMethodError err
628 fromException (Hugs.Exception.NoMethodError err) = Just (NoMethodError err)
629 fromException _ = Nothing
631 instance Exception NoMethodError
636 data NonTermination = NonTermination
637 INSTANCE_TYPEABLE0(NonTermination,nonTerminationTc,"NonTermination")
639 instance Show NonTermination where
640 showsPrec _ NonTermination = showString "<<loop>>"
643 instance Exception NonTermination where
644 toException NonTermination = Hugs.Exception.NonTermination
645 fromException Hugs.Exception.NonTermination = Just NonTermination
646 fromException _ = Nothing
648 instance Exception NonTermination
653 data NestedAtomically = NestedAtomically
654 INSTANCE_TYPEABLE0(NestedAtomically,nestedAtomicallyTc,"NestedAtomically")
656 instance Show NestedAtomically where
657 showsPrec _ NestedAtomically = showString "Control.Concurrent.STM.atomically was nested"
659 instance Exception NestedAtomically
663 instance Exception Dynamic
665 #endif /* __GLASGOW_HASKELL__ || __HUGS__ */
667 #ifdef __GLASGOW_HASKELL__
668 recSelError, recConError, irrefutPatError, runtimeError,
669 nonExhaustiveGuardsError, patError, noMethodBindingError
670 :: Addr# -> a -- All take a UTF8-encoded C string
672 recSelError s = throw (RecSelError ("No match in record selector "
673 ++ unpackCStringUtf8# s)) -- No location info unfortunately
674 runtimeError s = error (unpackCStringUtf8# s) -- No location info unfortunately
676 nonExhaustiveGuardsError s = throw (PatternMatchFail (untangle s "Non-exhaustive guards in"))
677 irrefutPatError s = throw (PatternMatchFail (untangle s "Irrefutable pattern failed for pattern"))
678 recConError s = throw (RecConError (untangle s "Missing field in record construction"))
679 noMethodBindingError s = throw (NoMethodError (untangle s "No instance nor default method for class operation"))
680 patError s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))
682 -- GHC's RTS calls this
683 nonTermination :: SomeException
684 nonTermination = toException NonTermination
686 -- GHC's RTS calls this
687 nestedAtomically :: SomeException
688 nestedAtomically = toException NestedAtomically