b4c511fecb09bd0a8a7a7fc529857f03ee67924d
[ghc-base.git] / GHC / Exception.lhs
1 \begin{code}
2 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
3 {-# OPTIONS_HADDOCK hide #-}
4 -----------------------------------------------------------------------------
5 -- |
6 -- Module      :  GHC.Exception
7 -- Copyright   :  (c) The University of Glasgow, 1998-2002
8 -- License     :  see libraries/base/LICENSE
9 -- 
10 -- Maintainer  :  cvs-ghc@haskell.org
11 -- Stability   :  internal
12 -- Portability :  non-portable (GHC extensions)
13 --
14 -- Exceptions and exception-handling functions.
15 -- 
16 -----------------------------------------------------------------------------
17
18 -- #hide
19 module GHC.Exception
20         ( module GHC.Exception,
21           throwIO, ioError )
22   where
23
24 import Data.Maybe
25 import {-# SOURCE #-} Data.Typeable
26 import GHC.Base
27 import GHC.IOBase hiding (Exception)
28 import qualified GHC.IOBase
29 import GHC.Show
30 \end{code}
31
32 %*********************************************************
33 %*                                                      *
34 \subsection{Exceptions}
35 %*                                                      *
36 %*********************************************************
37
38 \begin{code}
39 data SomeException = forall e . Exception e => SomeException e
40     deriving Typeable
41
42 instance Show SomeException where
43     showsPrec p (SomeException e) = showsPrec p e
44
45 class (Typeable e, Show e) => Exception e where
46     toException   :: e -> SomeException
47     fromException :: SomeException -> Maybe e
48
49     toException = SomeException
50     fromException (SomeException e) = cast e
51
52 instance Exception SomeException where
53     toException se = se
54     fromException = Just
55 \end{code}
56
57 For now at least, make the monolithic Exception type an instance.
58
59 \begin{code}
60 instance Exception GHC.IOBase.Exception
61 \end{code}
62
63 %*********************************************************
64 %*                                                      *
65 \subsection{Primitive catch and throw}
66 %*                                                      *
67 %*********************************************************
68
69 catchException used to handle the passing around of the state to the
70 action and the handler.  This turned out to be a bad idea - it meant
71 that we had to wrap both arguments in thunks so they could be entered
72 as normal (remember IO returns an unboxed pair...).
73
74 Now catch# has type
75
76     catch# :: IO a -> (b -> IO a) -> IO a
77
78 (well almost; the compiler doesn't know about the IO newtype so we
79 have to work around that in the definition of catchException below).
80
81 \begin{code}
82 catchException :: Exception e => IO a -> (e -> IO a) -> IO a
83 catchException (IO io) handler = IO $ catch# io handler'
84     where handler' e = case fromException e of
85                        Just e' -> unIO (handler e')
86                        Nothing -> raise# e
87
88 catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a
89 catchAny (IO io) handler = IO $ catch# io handler'
90     where handler' (SomeException e) = unIO (handler e)
91
92 -- | The 'catch' function establishes a handler that receives any 'IOError'
93 -- raised in the action protected by 'catch'.  An 'IOError' is caught by
94 -- the most recent handler established by 'catch'.  These handlers are
95 -- not selective: all 'IOError's are caught.  Exception propagation
96 -- must be explicitly provided in a handler by re-raising any unwanted
97 -- exceptions.  For example, in
98 --
99 -- > f = catch g (\e -> if IO.isEOFError e then return [] else ioError e)
100 --
101 -- the function @f@ returns @[]@ when an end-of-file exception
102 -- (cf. 'System.IO.Error.isEOFError') occurs in @g@; otherwise, the
103 -- exception is propagated to the next outer handler.
104 --
105 -- When an exception propagates outside the main program, the Haskell
106 -- system prints the associated 'IOError' value and exits the program.
107 --
108 -- Non-I\/O exceptions are not caught by this variant; to catch all
109 -- exceptions, use 'Control.Exception.catch' from "Control.Exception".
110 catch           :: IO a -> (IOError -> IO a) -> IO a 
111 catch m k       =  catchException m handler
112   where handler (IOException err)   = k err
113         handler other               = throw other
114
115 -- | Throw an exception.  Exceptions may be thrown from purely
116 -- functional code, but may only be caught within the 'IO' monad.
117 throw :: Exception e => e -> a
118 throw e = raise# (toException e)
119
120 -- | A variant of 'throw' that can be used within the 'IO' monad.
121 --
122 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
123 -- two functions are subtly different:
124 --
125 -- > throw e   `seq` x  ===> throw e
126 -- > throwIO e `seq` x  ===> x
127 --
128 -- The first example will cause the exception @e@ to be raised,
129 -- whereas the second one won\'t.  In fact, 'throwIO' will only cause
130 -- an exception to be raised when it is used within the 'IO' monad.
131 -- The 'throwIO' variant should be used in preference to 'throw' to
132 -- raise an exception within the 'IO' monad because it guarantees
133 -- ordering with respect to other 'IO' operations, whereas 'throw'
134 -- does not.
135 throwIO :: Exception e => e -> IO a
136 throwIO e = IO (raiseIO# (toException e))
137 \end{code}
138
139
140 %*********************************************************
141 %*                                                      *
142 \subsection{Controlling asynchronous exception delivery}
143 %*                                                      *
144 %*********************************************************
145
146 \begin{code}
147 -- | Applying 'block' to a computation will
148 -- execute that computation with asynchronous exceptions
149 -- /blocked/.  That is, any thread which
150 -- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be
151 -- blocked until asynchronous exceptions are enabled again.  There\'s
152 -- no need to worry about re-enabling asynchronous exceptions; that is
153 -- done automatically on exiting the scope of
154 -- 'block'.
155 --
156 -- Threads created by 'Control.Concurrent.forkIO' inherit the blocked
157 -- state from the parent; that is, to start a thread in blocked mode,
158 -- use @block $ forkIO ...@.  This is particularly useful if you need to
159 -- establish an exception handler in the forked thread before any
160 -- asynchronous exceptions are received.
161 block :: IO a -> IO a
162
163 -- | To re-enable asynchronous exceptions inside the scope of
164 -- 'block', 'unblock' can be
165 -- used.  It scopes in exactly the same way, so on exit from
166 -- 'unblock' asynchronous exception delivery will
167 -- be disabled again.
168 unblock :: IO a -> IO a
169
170 block (IO io) = IO $ blockAsyncExceptions# io
171 unblock (IO io) = IO $ unblockAsyncExceptions# io
172
173 -- | returns True if asynchronous exceptions are blocked in the
174 -- current thread.
175 blocked :: IO Bool
176 blocked = IO $ \s -> case asyncExceptionsBlocked# s of
177                         (# s', i #) -> (# s', i /=# 0# #)
178 \end{code}
179
180 \begin{code}
181 -- | Forces its argument to be evaluated when the resultant 'IO' action
182 -- is executed.  It can be used to order evaluation with respect to
183 -- other 'IO' operations; its semantics are given by
184 --
185 -- >   evaluate x `seq` y    ==>  y
186 -- >   evaluate x `catch` f  ==>  (return $! x) `catch` f
187 -- >   evaluate x >>= f      ==>  (return $! x) >>= f
188 --
189 -- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
190 -- same as @(return $! x)@.  A correct definition is
191 --
192 -- >   evaluate x = (return $! x) >>= return
193 --
194 evaluate :: a -> IO a
195 evaluate a = IO $ \s -> case a `seq` () of () -> (# s, a #)
196         -- NB. can't write  
197         --      a `seq` (# s, a #)
198         -- because we can't have an unboxed tuple as a function argument
199 \end{code}