Exceptions: Difference between revisions

Content added Content deleted
(UCB Logo)
(added haskell i think)
Line 222: Line 222:
Note that CATCH only restores the stack pointers, not the stack values, so any values that were changed during the execution of the token will have undefined values. In practice, this means writing code to clean up the stack, like this:
Note that CATCH only restores the stack pointers, not the stack values, so any values that were changed during the execution of the token will have undefined values. In practice, this means writing code to clean up the stack, like this:
10 ['] myfun catch if drop then
10 ['] myfun catch if drop then

=={{header|Haskell}}==
Exceptions can be implemented using monads; no special syntax is necessary.[http://haskell.org/haskellwiki/Exception] In GHC, specialized functionality for exceptions are provided by the <code>Control.Exception</code> module.

===Defining exceptions===
The type "Exception", which contains pre-defined exceptions, cannot be extended. You can however use "dynamic exceptions", which can be of any type that is of "Typeable" class. <!-- Somebody look over this; I don't really understand it. -->

===Throw exceptions===
In the context of the IO monad, use "throwIO" to throw exceptions; the expression will return any type:
do {- ... -}
throwIO SomeException

In purely functional context, use "throw" to throw exceptions; the expression will match any type:
if condition then 3
else throw SomeException

To throw a user-defined exception, use "throwDyn":
if condition then 3
else throwDyn myException

===Catching exceptions===
The "catch" function performs the whole try-catch stuff. It is usually used in infix style:
pattern-matches on the exception type and argument:
do
{- do IO computations here -}
`catch` \ex -> do
{- handle exception "ex" here -}

Note: Control.Exception's "catch" is different than Prelude's "catch".

To catch a user-defined exception, use "catchDyn":
do
{- do IO computations here -}
`catchDyn` \ex -> do
{- handle exception "ex" here -}


=={{header|J}}==
=={{header|J}}==