Exceptions: Difference between revisions

From Rosetta Code
Content added Content deleted
m (Fixed lang tags.)
Line 6: Line 6:
=={{header|Ada}}==
=={{header|Ada}}==
===Define an exception===
===Define an exception===
<lang ada>
<lang ada>Foo_Error : exception;</lang>
Foo_Error : exception;
</lang>
===Raise an exception===
===Raise an exception===
<lang ada>
<lang ada>procedure Foo is
procedure Foo is
begin
begin
raise Foo_Error;
raise Foo_Error;
end Foo;
end Foo;</lang>
</lang>
Re-raising once caught exception:
Re-raising once caught exception:
<lang ada>
<lang ada> ...
...
exception
exception
when Foo_Error =>
when Foo_Error =>
if ... then -- Alas, cannot handle it here,
if ... then -- Alas, cannot handle it here,
raise; -- continue propagation of
raise; -- continue propagation of
end if;
end if;</lang>
</lang>
===Handle an exception===
===Handle an exception===
<lang ada>
<lang ada>procedure Call_Foo is
procedure Call_Foo is
begin
begin
Foo;
Foo;
Line 35: Line 28:
when others =>
when others =>
... -- this catches all other exceptions
... -- this catches all other exceptions
end Call_Foo;
end Call_Foo;</lang>
</lang>
===Ada.Exceptions===
===Ada.Exceptions===
The standard package Ada.Exceptions provides a possibility to attach messages to exceptions, to get exception occurrence information and textual description of exceptions. The following example illustrates basic functionality of:
The standard package Ada.Exceptions provides a possibility to attach messages to exceptions, to get exception occurrence information and textual description of exceptions. The following example illustrates basic functionality of:
<lang ada>with Ada.Exceptions; use Ada.Exceptions;
<lang ada>
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;


Line 51: Line 42:
when Error : others =>
when Error : others =>
Put_Line ("Something is wrong here" & Exception_Information (Error));
Put_Line ("Something is wrong here" & Exception_Information (Error));
end Main;
end Main;</lang>
</lang>
=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
===Define an exception===
===Define an exception===
<lang algol68># a user defined object #
<pre>
# a user defined object #
MODE OBJECTFOO = STRUCT ( PROC (REF OBJECTFOO)BOOL foo event mended, ... );
MODE OBJECTFOO = STRUCT ( PROC (REF OBJECTFOO)BOOL foo event mended, ... );


PROC on foo event = (REF OBJECTFOO foo, PROC (REF OBJECTFOO)BOOL foo event)VOID: (
PROC on foo event = (REF OBJECTFOO foo, PROC (REF OBJECTFOO)BOOL foo event)VOID: (
foo event mended OF foo := foo event
foo event mended OF foo := foo event
);
);</lang>

</pre>
===Raise an exception===
===Raise an exception===
<lang algol68>OBJECTFOO foo proxy := foo base; # event routines are specific to an foo #
<pre>
OBJECTFOO foo proxy := foo base; # event routines are specific to an foo #


on foo event(foo proxy, raise foo event);
on foo event(foo proxy, raise foo event);
Line 73: Line 59:
# now raise example foo event #
# now raise example foo event #
IF NOT (foo event mended OF foo proxy)(foo proxy) THEN undefined # trace back # FI
IF NOT (foo event mended OF foo proxy)(foo proxy) THEN undefined # trace back # FI
OD;
OD;</lang>

</pre>
Re-raising once caught exception:
Re-raising once caught exception:
<lang algol68>...
<pre>
...
except foo event:
except foo event:
IF ... THEN # Alas, cannot handle it here continue propagation of #
IF ... THEN # Alas, cannot handle it here continue propagation of #
IF NOT (foo event mended OF foo base)(foo base) THEN undefined # trace back # FI
IF NOT (foo event mended OF foo base)(foo base) THEN undefined # trace back # FI
FI
FI</lang>
</pre>
===Handle an exception===
===Handle an exception===
<lang algol68>PROC raise foo event(REF OBJECTFOO foo)BOOL:
<pre>
PROC raise foo event(REF OBJECTFOO foo)BOOL:
IF mend foo(foo) THEN
IF mend foo(foo) THEN
TRUE # continue #
TRUE # continue #
Line 92: Line 73:
except foo event
except foo event
FALSE # OR fall back to default event routine #
FALSE # OR fall back to default event routine #
FI
FI</lang>
</pre>
===Standard Prelude "on event" routines===
===Standard Prelude "on event" routines===
ALGOL 68 uses event routines extensively in the "standard transput"
ALGOL 68 uses event routines extensively in the "standard transput"
Line 123: Line 103:
=={{header|AppleScript}}==
=={{header|AppleScript}}==
===try===
===try===
<lang applescript>try
try
set num to 1 / 0
set num to 1 / 0
--do something that might throw an error
--do something that might throw an error
end try
end try</lang>


===try-on error===
===try-on error===
<lang applescript>try
try
set num to 1 / 0
set num to 1 / 0
--do something that might throw an error
--do something that might throw an error
on error errMess number errNum
on error errMess number errNum
--errMess and number errNum are optional
--errMess and number errNum are optional
display alert "Error # " & errNum & return & errMess
display alert "Error # " & errNum & return & errMess
end try
end try</lang>


===error===
===error===
error "Error message." number 2000
<lang applescript>error "Error message." number 2000</lang>
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>
<lang AutoHotkey>foo()
foo()
If ErrorLevel
If ErrorLevel
Msgbox calling foo failed with: %ErrorLevel%
Msgbox calling foo failed with: %ErrorLevel%
Line 152: Line 131:
ErrorLevel = foo_error
ErrorLevel = foo_error
Return
Return
}</lang>
}

</lang>


=={{header|C}}==
=={{header|C}}==
Line 162: Line 139:
===try-catch===
===try-catch===


<lang c> #include <setjmp.h>
<lang c>#include <setjmp.h>
enum { MY_EXCEPTION = 1 }; /* any non-zero number */
enum { MY_EXCEPTION = 1 }; /* any non-zero number */
jmp_buf env;
jmp_buf env;
void foo()
void foo()
{
{
longjmp(env, MY_EXCEPTION); /* throw MY_EXCEPTION */
longjmp(env, MY_EXCEPTION); /* throw MY_EXCEPTION */
}
}
void call_foo()
void call_foo()
{
{
switch (setjmp(env)) {
switch (setjmp(env)) {
case 0: /* try */
case 0: /* try */
foo();
foo();
break;
break;
case MY_EXCEPTION: /* catch MY_EXCEPTION */
case MY_EXCEPTION: /* catch MY_EXCEPTION */
/* handle exceptions of type MY_EXCEPTION */
/* handle exceptions of type MY_EXCEPTION */
break;
break;
default:
default:
/* handle any type of exception not handled by above catches */
/* handle any type of exception not handled by above catches */
}
}
}</lang>
}</lang>


=={{header|C++}}==
=={{header|C++}}==
Line 195: Line 172:


===Defining exceptions===
===Defining exceptions===
<lang cpp>
<lang cpp>struct MyException
struct MyException
{
{
// data with info about exception
// data with info about exception
};
};</lang>
</lang>


There's also a class <tt>std::exception</tt> which you can, but are not required to derive your exception class from. The advantage of doing so is that you can catch unknown exceptions and still get some meaningful information out. There are also more specific classes like <tt>std::runtime_error</tt> which derive from <tt>std::exception</tt>.
There's also a class <tt>std::exception</tt> which you can, but are not required to derive your exception class from. The advantage of doing so is that you can catch unknown exceptions and still get some meaningful information out. There are also more specific classes like <tt>std::runtime_error</tt> which derive from <tt>std::exception</tt>.


<lang cpp>
<lang cpp>#include <exception>
#include <exception>
struct MyException: std::exception
struct MyException: std::exception
{
{
char const* what() const throw() { return "description"; }
char const* what() const throw() { return "description"; }
}</lang>
}
</lang>


Note that in principle you can throw any copyable type as exception, including built-in types.
Note that in principle you can throw any copyable type as exception, including built-in types.


===Throw exceptions===
===Throw exceptions===
<lang cpp>// this function can throw any type of exception
<lang cpp>
// this function can throw any type of exception
void foo()
void foo()
{
{
Line 232: Line 204:
{
{
throw MyException();
throw MyException();
}</lang>
}
</lang>


===Catching exceptions===
===Catching exceptions===
<lang cpp>
<lang cpp>try {
try {
foo();
}
foo();
catch (MyException &exc)
}
{
catch (MyException &exc)
// handle exceptions of type MyException and derived
{
}
// handle exceptions of type MyException and derived
catch (std::exception &exc)
}
{
catch (std::exception &exc)
// handle exceptions derived from std::exception, which were not handled by above catches
{
// e.g.
// handle exceptions derived from std::exception, which were not handled by above catches
std::cerr << exc.what() << std::endl;
// e.g.
}
std::cerr << exc.what() << std::endl;
catch (...)
}
{
catch (...)
// handle any type of exception not handled by above catches
{
}</lang>
// handle any type of exception not handled by above catches
}
</lang>


=={{header|C sharp|C #}}==
=={{header|C sharp|C#}}==
{{works with|Visual Studio|2005}}
{{works with|Visual Studio|2005}}


===Defining exceptions===
===Defining exceptions===
public class MyException : Exception
<lang csharp>public class MyException : Exception
{
{
// data with info about exception
// data with info about exception
};</lang>
};


===Throw exceptions===
===Throw exceptions===
void foo()
<lang csharp>void foo()
{
{
throw MyException();
throw MyException();
}</lang>
}


===Catching exceptions===
===Catching exceptions===
try {
<lang csharp>try {
foo();
foo();
}
}
catch (MyException e)
catch (MyException e)
{
{
// handle exceptions of type MyException and derived
// handle exceptions of type MyException and derived
}
}
catch
catch
{
{
// handle any type of exception not handled by above catches
// handle any type of exception not handled by above catches
}</lang>
}




Line 289: Line 258:
inside &lt;cfscript&gt;:
inside &lt;cfscript&gt;:


try {
<lang cfm>try {
foo();
foo();
} catch (Any e) {
} catch (Any e) {
// handle exception e
// handle exception e
}</lang>
}


otherwise:
otherwise:
&lt;cftry&gt;
<lang cfm><cftry>
&lt;cfcatch type="Database|..."&gt;
<cfcatch type="Database|...">
&lt;/cfcatch&gt;
</cfcatch>
&lt;/cftry&gt;
</cftry></lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 367: Line 336:
<code>throw</code> is the built-in ''function'' which throws exceptions in the conventional sense: control goes to the <code>catch</code> block of the most recently entered <code>try</code>/<code>catch</code> construct.
<code>throw</code> is the built-in ''function'' which throws exceptions in the conventional sense: control goes to the <code>catch</code> block of the most recently entered <code>try</code>/<code>catch</code> construct.


<lang e>
<lang e>def nameOf(arg :int) {
def nameOf(arg :int) {
if (arg == 43) {
if (arg == 43) {
return "Bob"
return "Bob"
Line 417: Line 385:
return ["notok", exceptionObj]
return ["notok", exceptionObj]
}
}
}</lang>
}
</lang>


<lang e>? catching(42)
<lang e>? catching(42)
Line 453: Line 420:
=={{header|Factor}}==
=={{header|Factor}}==
===Throw Exceptions===
===Throw Exceptions===
"Install Linux, Problem Solved" throw
<lang factor>"Install Linux, Problem Solved" throw


TUPLE: velociraptor ;
TUPLE: velociraptor ;
\ velociraptor new throw
\ velociraptor new throw</lang>


Or a shorthand for this:
Or a shorthand for this:
ERROR: velociraptor ;
<lang factor>ERROR: velociraptor ;
velociraptor
velociraptor</lang>


===Catch Exceptions===
===Catch Exceptions===
! Preferred exception handling
<lang factor>! Preferred exception handling
: try-foo
: try-foo
[ foo ] [ foo-failed ] recover ;
[ foo ] [ foo-failed ] recover ;


: try-bar
: try-bar
[ bar ] [ bar-errored ] [ bar-always ] cleanup ;
[ bar ] [ bar-errored ] [ bar-always ] cleanup ;


! Used rarely
! Used rarely
[ "Fail" throw ] try ! throws a "Fail"
[ "Fail" throw ] try ! throws a "Fail"
[ "Fail" throw ] catch ! returns "Fail"
[ "Fail" throw ] catch ! returns "Fail"
[ "Hi" print ] catch ! returns f (looks the same as throwing f; don't throw f)
[ "Hi" print ] catch ! returns f (looks the same as throwing f; don't throw f)
[ f throw ] catch ! returns f, bad! use recover or cleanup instead
[ f throw ] catch ! returns f, bad! use recover or cleanup instead</lang>


=={{header|Forth}}==
=={{header|Forth}}==
Line 480: Line 447:


===Throw Exceptions===
===Throw Exceptions===
: f ( -- ) 1 throw ." f " ; \ will throw a "1"
<lang forth>: f ( -- ) 1 throw ." f " ; \ will throw a "1"
: g ( -- ) 0 throw ." g " ; \ does not throw
: g ( -- ) 0 throw ." g " ; \ does not throw</lang>


===Catch Exceptions===
===Catch Exceptions===
: report ( n -- ) ?dup if ." caught " . else ." no throw" then ;
<lang forth>: report ( n -- ) ?dup if ." caught " . else ." no throw" then ;
: test ( -- )
: test ( -- )
['] f catch report
['] f catch report
['] g catch report ;
['] g catch report ;</lang>
test example. (Output shown in bold)
test example. (Output shown in bold)
cr test
<lang forth>cr test
'''caught 1 g no throw ok'''
'''caught 1 g no throw ok'''</lang>


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
<lang forth>10 ['] myfun catch if drop then</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==
Line 503: Line 470:
===Throw exceptions===
===Throw exceptions===
In the context of the IO monad, use "throwIO" to throw exceptions; the expression will return any type:
In the context of the IO monad, use "throwIO" to throw exceptions; the expression will return any type:
do {- ... -}
<lang haskell>do {- ... -}
throwIO SomeException
throwIO SomeException</lang>


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


To throw a user-defined exception, use "throwDyn":
To throw a user-defined exception, use "throwDyn":
if condition then 3
<lang haskell>if condition then 3
else throwDyn myException
else throwDyn myException</lang>


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


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


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


=={{header|J}}==
=={{header|J}}==
Line 538: Line 505:
An exception in an explicit definition can be detected with <tt>try.</tt> and <tt>catcht.</tt> and can be thrown with <tt> throw. </tt> as seen below.
An exception in an explicit definition can be detected with <tt>try.</tt> and <tt>catcht.</tt> and can be thrown with <tt> throw. </tt> as seen below.


pickyPicky =: verb define
<lang j> pickyPicky =: verb define
if. y-:'bad argument' do.
if. y-:'bad argument' do.
throw.
throw.
else.
else.
'thanks!'
'thanks!'
end.
end.
)
)
tryThis =: verb define
tryThis =: verb define
try.
try.
pickyPicky y
pickyPicky y
catcht.
catcht.
'Uh oh!'
'Uh oh!'
end.
end.
)
)

tryThis 'bad argument'
tryThis 'bad argument'
Uh oh!
Uh oh!</lang>


=={{header|Java}}==
=={{header|Java}}==
Line 561: Line 528:


===Defining exceptions===
===Defining exceptions===
//Checked exception
<lang java>//Checked exception
public class MyException extends Exception {
public class MyException extends Exception {
//Put specific info in here
//Put specific info in here
}
}


//Unchecked exception
//Unchecked exception
public class MyRuntimeException extends RuntimeException {}
public class MyRuntimeException extends RuntimeException {}</lang>


===Throw exceptions===
===Throw exceptions===
public void fooChecked() throws MyException {
<lang java>public void fooChecked() throws MyException {
throw new MyException();
throw new MyException();
}
}


public void fooUnchecked() {
public void fooUnchecked() {
throw new MyRuntimeException();
throw new MyRuntimeException();
}</lang>
}


===Catching exceptions===
===Catching exceptions===
try {
<lang java>try {
fooChecked();
fooChecked();
}
}
catch(MyException exc) {
catch(MyException exc) {
//Catch only your specified type of exception
//Catch only your specified type of exception
}
}
catch(Exception exc) {
catch(Exception exc) {
//Catch any non-system error exception
//Catch any non-system error exception
}
}
catch(Throwable exc) {
catch(Throwable exc) {
//Catch everything including system errors (not recommended)
//Catch everything including system errors (not recommended)
}
}
finally {
finally {
//This code is always executed after exiting the try block
//This code is always executed after exiting the try block
}</lang>
}


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 599: Line 566:
===Throwing exceptions===
===Throwing exceptions===


function doStuff() {
<lang javascript>function doStuff() {
throw new Error('Not implemented!');
throw new Error('Not implemented!');
}</lang>
}


===Catching exceptions===
===Catching exceptions===


try {
<lang javascript>try {
element.attachEvent('onclick', doStuff);
element.attachEvent('onclick', doStuff);
}
}
catch(e if e instanceof TypeError) {
catch(e if e instanceof TypeError) {
element.addEventListener('click', doStuff, false);
element.addEventListener('click', doStuff, false);
}
}
finally {
finally {
eventSetup = true;
eventSetup = true;
}</lang>
}


=={{header|Logo}}==
=={{header|Logo}}==
{{works with|UCB Logo}}
{{works with|UCB Logo}}
to div.checked :a :b
<lang logo>to div.checked :a :b
if :b = 0 [(throw "divzero 0)]
if :b = 0 [(throw "divzero 0)]
output :a / :b
output :a / :b
end
end
to div.safely :a :b
to div.safely :a :b
output catch "divzero [div.checked :a :b]
output catch "divzero [div.checked :a :b]
end
end</lang>
There are also some predefined exceptions:
There are also some predefined exceptions:
* '''throw "toplevel''' returns to the interactive prompt if uncaught (like control-C)
* '''throw "toplevel''' returns to the interactive prompt if uncaught (like control-C)
Line 636: Line 603:
fail.mk
fail.mk


all:
<lang make>all:
false
false</lang>


Using -@ to ignore the exception.
Using -@ to ignore the exception.
Line 643: Line 610:
catch.mk
catch.mk


all:
<lang make>all:
-@make -f fail.mk
-@make -f fail.mk</lang>


Using explicit exit 0 to ignore the exception.
Using explicit exit 0 to ignore the exception.
Line 650: Line 617:
catch.mk
catch.mk


all:
<lang make>all:
make -f fail.mk; exit 0
make -f fail.mk; exit 0</lang>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
Line 665: Line 632:
...
...
RAISE EndOfFile;
RAISE EndOfFile;
...
...</lang>
</lang>


===Catching exceptions===
===Catching exceptions===
Line 680: Line 646:
FINALLY
FINALLY
CleanupFoo(); (* always executed *)
CleanupFoo(); (* always executed *)
END;
END;</lang>
</lang>




Line 698: Line 663:


MOO also has a finally statement:
MOO also has a finally statement:
<lang modula3>try
<lang moo>try
this:foo();
this:foo();
finally
finally
Line 744: Line 709:
===Defining exceptions===
===Defining exceptions===
Like constructors, exceptions may or may not have an argument:
Like constructors, exceptions may or may not have an argument:
exception My_Exception;;
<lang ocaml>exception My_Exception;;
exception Another_Exception of string;;
exception Another_Exception of string;;</lang>


===Throw exceptions===
===Throw exceptions===
Throw exceptions with the "raise" function; the expression will match any type:
Throw exceptions with the "raise" function; the expression will match any type:
let foo x =
<lang ocaml>let foo x =
match x with
match x with
1 -> raise My_Exception
1 -> raise My_Exception
| 2 -> raise (Another_Exception "hi mom")
| 2 -> raise (Another_Exception "hi mom")
| _ -> 5
| _ -> 5
;;</lang>
;;


===Catching exceptions===
===Catching exceptions===
The "with" syntax pattern-matches on the exception type and argument:
The "with" syntax pattern-matches on the exception type and argument:
<lang ocaml>try
try
string_of_int (foo 2)
string_of_int (foo 2)
with
with
My_Exception -> "got my exception"
My_Exception -> "got my exception"
| Another_Exception s -> s
| Another_Exception s -> s
| _ -> "unknown exception"
| _ -> "unknown exception"</lang>


=={{header|Perl}}==
=={{header|Perl}}==
Line 787: Line 752:
Exceptions were not available prior to PHP 5.0
Exceptions were not available prior to PHP 5.0
===Define exceptions===
===Define exceptions===
class MyException extends Exception
<lang php>class MyException extends Exception
{
{
// Custom exception attributes & methods
// Custom exception attributes & methods
}</lang>
}


===Throwing exceptions===
===Throwing exceptions===
function throwsException()
<lang php>function throwsException()
{
{
throw new Exception('Exception message');
throw new Exception('Exception message');
}</lang>
}
===Catching Exceptions===
===Catching Exceptions===
try {
<lang php>try {
throwsException();
throwsException();
} catch (Exception $e) {
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
echo 'Caught exception: ' . $e->getMessage();
}</lang>
}


=={{header|Pop11}}==
=={{header|Pop11}}==
Line 808: Line 773:
===Throwing exceptions===
===Throwing exceptions===


<lang pop11>define throw_exception();
<pre>
define throw_exception();
throw([my_exception my_data]);
throw([my_exception my_data]);
enddefine;
enddefine;</lang>
</pre>


===Catching exceptions===
===Catching exceptions===


<lang pop11>define main();
<pre>
define main();
vars cargo;
vars cargo;
define catcher();
define catcher();
Line 826: Line 788:
enddefine;
enddefine;


main();
main();</lang>
</pre>


=={{header|Python}}==
=={{header|Python}}==
Line 833: Line 794:
===Defining an exception===
===Defining an exception===


<lang python> import exceptions
<lang python>import exceptions
class SillyError(exceptions.Exception):
class SillyError(exceptions.Exception):
def __init__(self,args=None):
def __init__(self,args=None):
self.args=args</lang>
self.args=args</lang>


Note: In most cases new exceptions are defined simply using the ''pass'' statement. For example:
Note: In most cases new exceptions are defined simply using the ''pass'' statement. For example:


<lang python>
<lang python>class MyInvalidArgument(ValueError):
pass</lang>
class MyInvalidArgument(ValueError):
pass
</lang>


This example makes "MyInvalidArgument" an type of ValueError (one of the built-in exceptions). It's simply declared as a subclass of the existing exception and no over-riding is necessary. (An except clause for ValueError would catch MyInvalidArgument exceptions ... but one's code could insert a more specific exception handler for the more specific type of exception).
This example makes "MyInvalidArgument" an type of ValueError (one of the built-in exceptions). It's simply declared as a subclass of the existing exception and no over-riding is necessary. (An except clause for ValueError would catch MyInvalidArgument exceptions ... but one's code could insert a more specific exception handler for the more specific type of exception).
Line 896: Line 855:
=={{header|Raven}}==
=={{header|Raven}}==


42 as custom_error
<lang raven>42 as custom_error

define foo
define foo
custom_error throw
custom_error throw

try
try
foo
foo
catch
catch
custom_error =
custom_error =
if 'oops' print
if 'oops' print</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
Line 951: Line 910:
Ruby has a separate exception-like system that is meant to be used to exit out of deep executions that are not errors.
Ruby has a separate exception-like system that is meant to be used to exit out of deep executions that are not errors.


<lang python>def foo
<lang ruby>def foo
throw :done
throw :done
end
end
Line 965: Line 924:
===Handling Exceptions===
===Handling Exceptions===


<lang slate>
<lang slate>se@(SceneElement traits) doWithRestart: block
se@(SceneElement traits) doWithRestart: block
[
[
block handlingCases: {Abort -> [| :_ | ^ Nil]}
block handlingCases: {Abort -> [| :_ | ^ Nil]}
].
].</lang>

</lang>


===Define Exceptions===
===Define Exceptions===


<lang slate>
<lang slate>conditions define: #Abort &parents: {Restart}.
conditions define: #Abort &parents: {Restart}.
"An Abort is a Restart which exits the computation, unwinding the stack."
"An Abort is a Restart which exits the computation, unwinding the stack."


Line 993: Line 948:
[
[
c tryHandlers
c tryHandlers
].
].</lang>

</lang>


===Throwing Exceptions===
===Throwing Exceptions===
<lang slate>(fileName endsWith: '.image') ifTrue: [error: 'Image filename specified where Slate source expected. Make sure you run slate with the -i flag to specify an image.'].</lang>
<lang slate>
(fileName endsWith: '.image') ifTrue: [error: 'Image filename specified where Slate source expected. Make sure you run slate with the -i flag to specify an image.'].

</lang>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
===Define Exceptions===
===Define Exceptions===
exception MyException;
<lang sml>exception MyException;
exception MyDataException of int; (* can be any first-class type, not just int *)
exception MyDataException of int; (* can be any first-class type, not just int *)</lang>


===Throw Exceptions===
===Throw Exceptions===
fun f() = raise MyException;
<lang sml>fun f() = raise MyException;
fun g() = raise MyDataException 22;
fun g() = raise MyDataException 22;</lang>


===Catch Exceptions===
===Catch Exceptions===
val x = f() handle MyException => 22;
<lang sml>val x = f() handle MyException => 22;
val y = f() handle MyDataException x => x;
val y = f() handle MyDataException x => x;</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
Line 1,063: Line 1,013:


throwing exceptions
throwing exceptions
[myproc
<lang v>[myproc
['new error' 1 2 3] throw
['new error' 1 2 3] throw
'should not come here' puts
'should not come here' puts
].</lang>
].


catching them
catching them


[myproc] [puts] catch
<lang v>[myproc] [puts] catch
=[new error 1 2 3]
=[new error 1 2 3]</lang>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==


===Defining exceptions===
===Defining exceptions===
Class MyException
<lang vbnet>Class MyException
Inherits Exception
Inherits Exception
'data with info about exception
'data with info about exception
End Class
End Class</lang>
===Throw exceptions===
===Throw exceptions===
Sub foo()
<lang vbnet>Sub foo()
Throw New MyException
Throw New MyException
End Sub
End Sub</lang>


===Catching exceptions===
===Catching exceptions===
Sub bar()
<lang vbnet>Sub bar()
Try
Try
foo()
foo()
Catch e As MyException When e.Data.Contains("Foo")
Catch e As MyException When e.Data.Contains("Foo")
' handle exceptions of type MyException when the exception contains specific data
' handle exceptions of type MyException when the exception contains specific data
Catch e As MyException
Catch e As MyException
' handle exceptions of type MyException and derived exceptions
' handle exceptions of type MyException and derived exceptions
Catch e As Exception
Catch e As Exception
' handle any type of exception not handled by above catches
' handle any type of exception not handled by above catches
Finally
Finally
'code here occurs whether or not there was an exception
'code here occurs whether or not there was an exception
End Try
End Try
End Sub
End Sub</lang>


{{omit from|M4}}
{{omit from|M4}}

Revision as of 02:28, 20 November 2009

Task
Exceptions
You are encouraged to solve this task according to the task description, using any language you may know.
Control Structures

These are examples of control structures. You may also be interested in:

This task is to give an example of an exception handling routine and to "throw" a new exception.

Cf. Exceptions Through Nested Calls

Ada

Define an exception

<lang ada>Foo_Error : exception;</lang>

Raise an exception

<lang ada>procedure Foo is begin

  raise Foo_Error;

end Foo;</lang> Re-raising once caught exception: <lang ada> ... exception

  when Foo_Error =>
     if ... then -- Alas, cannot handle it here,
        raise;   -- continue propagation of
     end if;</lang>

Handle an exception

<lang ada>procedure Call_Foo is begin

  Foo;

exception

  when Foo_Error =>
     ... -- do something
  when others =>
     ... -- this catches all other exceptions

end Call_Foo;</lang>

Ada.Exceptions

The standard package Ada.Exceptions provides a possibility to attach messages to exceptions, to get exception occurrence information and textual description of exceptions. The following example illustrates basic functionality of: <lang ada>with Ada.Exceptions; use Ada.Exceptions; with Ada.Text_IO; use Ada.Text_IO;

procedure Main is begin

  ...
  Raise_Exception (Foo_Error'Identity, "This is the exception message");
  ..

exception

  when Error : others =>
     Put_Line ("Something is wrong here" & Exception_Information (Error));

end Main;</lang>

ALGOL 68

Define an exception

<lang algol68># a user defined object # MODE OBJECTFOO = STRUCT ( PROC (REF OBJECTFOO)BOOL foo event mended, ... );

PROC on foo event = (REF OBJECTFOO foo, PROC (REF OBJECTFOO)BOOL foo event)VOID: (

 foo event mended OF foo := foo event

);</lang>

Raise an exception

<lang algol68>OBJECTFOO foo proxy := foo base; # event routines are specific to an foo #

on foo event(foo proxy, raise foo event);

WHILE TRUE DO

 # now raise example foo event #
 IF NOT (foo event mended OF foo proxy)(foo proxy) THEN undefined # trace back # FI

OD;</lang> Re-raising once caught exception: <lang algol68>... except foo event:

 IF ... THEN # Alas, cannot handle it here continue propagation of #
   IF NOT (foo event mended OF foo base)(foo base) THEN undefined # trace back # FI
 FI</lang>

Handle an exception

<lang algol68>PROC raise foo event(REF OBJECTFOO foo)BOOL:

 IF mend foo(foo) THEN
   TRUE # continue #
 ELSE
   except foo event
   FALSE # OR fall back to default event routine #
 FI</lang>

Standard Prelude "on event" routines

ALGOL 68 uses event routines extensively in the "standard transput" (stdio) to manage the various events that arise when data is read (or written) to a file or external device. The built in "on event" routines are:

  • on char error - if the character transput (input or output) in cannot be converted to the standard character set.
  • on format error - if the format specified is incompatible to the data being transput (input or output)
  • on line end - if an end of line was read while the program was "transputting" data
  • on logical file end - if the end of data was encounted during transput
  • on page end - if the end of a page was encounted during transput
  • on physical file end - if the end of physical media was encounted during transput
  • on value error - if the data transput was incompatibly with the variable being transput, eg a letter when a digit was expected.

All of the above allow the programmer to define a user created event routine when a particular event happens to a particular FILE. When such an event routine is called, then the routine can use any of the standard prelude routine to reposition the FILE and rectify the detected event, eg:

  • space or back space
  • new line, new page, set or reset.

For example: these may notify the operator to mount a new tape (in the case of physical file end).

The handler is permitted to return TRUE depending on whether the event has been handled and the program can can continue. And FALSE is when event remains unhandled, and the standard prelude event routine should be used. The handler is also permitted to exit to a label (without returning anything) if the user defined event routine determines that processing is complete.

AppleScript

try

<lang applescript>try

   set num to 1 / 0
   --do something that might throw an error

end try</lang>

try-on error

<lang applescript>try

   set num to 1 / 0
   --do something that might throw an error

on error errMess number errNum

   --errMess and number errNum are optional
   display alert "Error # " & errNum & return & errMess

end try</lang>

error

<lang applescript>error "Error message." number 2000</lang>

AutoHotkey

<lang AutoHotkey>foo() If ErrorLevel

 Msgbox calling foo failed with:  %ErrorLevel%

foo() {

 If success
   Return
 Else
   ErrorLevel = foo_error
 Return

}</lang>

C

The setjmp()/longjmp() functions in the C standard library header <setjmp.h> are typically used for exception handling.

try-catch

<lang c>#include <setjmp.h>

enum { MY_EXCEPTION = 1 }; /* any non-zero number */

jmp_buf env;

void foo() {

 longjmp(env, MY_EXCEPTION); /* throw MY_EXCEPTION */

}

void call_foo() {

 switch (setjmp(env)) {
 case 0:                     /* try */
   foo();
   break;
 case MY_EXCEPTION:          /* catch MY_EXCEPTION */
   /* handle exceptions of type MY_EXCEPTION */
   break;
 default:
   /* handle any type of exception not handled by above catches */
 }

}</lang>

C++

C++ has no finally construct. Instead you can do this in the destructor of an object on the stack, which will be called if an exception is thrown.

The exception can be of any type, this includes int's, other primitives, as well as objects.

Defining exceptions

<lang cpp>struct MyException {

 // data with info about exception

};</lang>

There's also a class std::exception which you can, but are not required to derive your exception class from. The advantage of doing so is that you can catch unknown exceptions and still get some meaningful information out. There are also more specific classes like std::runtime_error which derive from std::exception.

<lang cpp>#include <exception> struct MyException: std::exception {

 char const* what() const throw() { return "description"; }

}</lang>

Note that in principle you can throw any copyable type as exception, including built-in types.

Throw exceptions

<lang cpp>// this function can throw any type of exception void foo() {

 throw MyException();

}

// this function can only throw the types of exceptions that are listed void foo2() throw(MyException) {

 throw MyException();

}

// this function turns any exceptions other than MyException into std::bad_exception void foo3() throw(MyException, std::bad_exception) {

 throw MyException();

}</lang>

Catching exceptions

<lang cpp>try {

 foo();

} catch (MyException &exc) {

 // handle exceptions of type MyException and derived

} catch (std::exception &exc) {

 // handle exceptions derived from std::exception, which were not handled by above catches
 // e.g.
 std::cerr << exc.what() << std::endl;

} catch (...) {

 // handle any type of exception not handled by above catches

}</lang>

C#

Works with: Visual Studio version 2005

Defining exceptions

<lang csharp>public class MyException : Exception {

 // data with info about exception

};</lang>

Throw exceptions

<lang csharp>void foo() {

 throw MyException();

}</lang>

Catching exceptions

<lang csharp>try {

 foo();

} catch (MyException e) {

 // handle exceptions of type MyException and derived

} catch {

 // handle any type of exception not handled by above catches

}</lang>


ColdFusion

Catch Exceptions

inside <cfscript>:

<lang cfm>try {

 foo();

} catch (Any e) {

 // handle exception e

}</lang>

otherwise: <lang cfm><cftry> <cfcatch type="Database|..."> </cfcatch> </cftry></lang>

Common Lisp

The Common Lisp condition system allows much more control over condition signaling and condition handling than many exception-based systems. The following example, however, simply defines a condition type, unexpected-odd-number, defines a function get-number which generates a random number, returning it if it is even, but signaling an unexpected-odd-number condition if it is odd. The function get-even-number uses handler-case to call get-number returning its result if no condition is signaled, and, in the case that an unexpected-odd-number condition is signaled, returning one plus the odd number.

<lang lisp>(define-condition unexpected-odd-number (error)

 ((number :reader number :initarg :number))
 (:report (lambda (condition stream)
            (format stream "Unexpected odd number: ~w."
                    (number condition)))))

(defun get-number (&aux (n (random 100)))

 (if (not (oddp n)) n
   (error 'unexpected-odd-number :number n)))

(defun get-even-number ()

 (handler-case (get-number)
   (unexpected-odd-number (condition)
     (1+ (number condition)))))</lang>

A good introduction to Lisp's condition system is the chapter Beyond Exception Handling: Conditions and Restarts from Peter Seibel's Practical Common Lisp.

In Common Lisp, there are functions throw and catch, but these are not related to the condition system. Rather, they provide another mechanism for non-local control transfer.

D

Throw Exceptions

<lang d>void test() {

 throw new Exception("Sample Exception");

}</lang>

Catch Exceptions

<lang d>void test2() {

 try test();
 catch (Exception ex) { writefln(ex); throw ex; /* rethrow */ }

}</lang>

In debug mode, stack traces can be generated via an external package, but the standard library does not support it by default.

Ways to implement finally

<lang d>void test3() {

 try test2();
 finally writefln("test3 finally");

}</lang> Or also with scope guards! <lang d>void test4() {

 scope(exit) writefln("Test4 done");
 scope(failure) writefln("Test4 exited by exception");
 scope(success) writefln("Test4 exited by return or function end");
 test2();

}</lang>

E

Exceptions

An exception object describes what the problem is and has nothing to do with control flow.

Due to E's ancestry as a JVM scripting language, E does not yet have any standard mechanism for user-defined exception types.

A string provided in place of an exception will be coerced to a generic exception object.

There are two control flow constructs used with exceptions: throw and eject.

Throw and catch

throw is the built-in function which throws exceptions in the conventional sense: control goes to the catch block of the most recently entered try/catch construct.

<lang e>def nameOf(arg :int) {

   if (arg == 43) {
       return "Bob"
   } else {
       throw("Who?")
   }

}

def catching(arg) {

   try {
       return ["ok", nameOf(arg)]
   } catch exceptionObj {
       return ["notok", exceptionObj]
   }

}</lang>

<lang e>? catching(42)

  1. value: ["not ok", problem: Who?]

? catching(43)

  1. value: ["ok", "Bob"]

? catching(45.7)

  1. value: ["not ok", problem: the float64 45.7 doesn't coerce to an int]</lang>

However, there is a problem here: exceptions accidentally produced or uncaught from inside a given module can lead to the calling program getting information about the internals that it shouldn't have (possibly a security problem). As a result of this, we are planning to move to a 'sealed exception' model where throw and catch have the same control flow, but only debuggers can see any information in a caught exception other than "a throw happened". For situations where the caller should have information about what happened, the ejector mechanism will be used.

Ejectors

Ejectors provide the same sort of "exit to catch block" control flow that throw/catch do, but with an explicit path rather than implicitly "nearest enclosing". Ejectors are also used as a general purpose control construct as well as for exceptions.

The escape ej { body } catch pat { catch block } construct creates an ejector object and binds it to ej, which is valid for as long as body is executing. An ejector object is a function; if it is called, then control immediately passes to the catch block, with its argument bound to pat.

The above code rewritten to use ejectors:

<lang e>def nameOf(arg :int, ejector) {

   if (arg == 43) {
       return "Bob"
   } else {
       ejector("Who?")
   }

}

def catching(arg) {

   escape unnamed {
       return ["ok", nameOf(arg, unnamed)]
   } catch exceptionObj {
       return ["notok", exceptionObj]
   }

}</lang>

<lang e>? catching(42)

  1. value: ["not ok", problem: Who?]

? catching(43)

  1. value: ["ok", "Bob"]

? catching(45.7)

  1. problem: the float64 45.7 doesn't coerce to an int</lang>

Note that the escape-catch block does not catch the coercion error resulting from passing a float64 instead of an int, since that is an (implicit) throw.

(One further refinement: While an ejector is an ordinary function, which does not return, it is generally desirable to protect against being supplied a function which unexpectedly does return. For this purpose we have throw.eject which calls the supplied function and throws if that function returns: throw.eject(ejector, "Who?"))

The benefit of using ejectors to communicate exceptions, besides the information-leak prevention described above, is that only exceptions intended to be handled by that catch block will be passed to it; unexpected internal errors will be handled by general try/catch handlers.

For example, suppose we have nameOf written as follows:

<lang e>var nameTable := null def nameOf(arg :int, ejector) {

   if (nameTable == null) {
       nameTable := <import:nameTableParser>.parseFile(<file:nameTable.txt>)
   }
   if (nameTable.maps(arg)) {
       return nameTable[arg]
   } else {
       ejector(makeNotFoundException("Who?"))
   }

}</lang>

Suppose that loading the parser, or reading the file, throws a NotFoundException (note this exception type was made up for this example). Even though it is of the same type as the "Who?" exception, it will not be caught by the caller's escape/catch block since it was not passed via the ejector, whereas a traditional "try { ... } catch ex :NotFoundException { ... }" as in other languages would, leading to incorrect handling of the error.

Factor

Throw Exceptions

<lang factor>"Install Linux, Problem Solved" throw

TUPLE: velociraptor ; \ velociraptor new throw</lang>

Or a shorthand for this: <lang factor>ERROR: velociraptor ; velociraptor</lang>

Catch Exceptions

<lang factor>! Preferred exception handling

try-foo
   [ foo ] [ foo-failed ] recover ;
try-bar
   [ bar ] [ bar-errored ] [ bar-always ] cleanup ;

! Used rarely [ "Fail" throw ] try  ! throws a "Fail" [ "Fail" throw ] catch ! returns "Fail" [ "Hi" print ] catch  ! returns f (looks the same as throwing f; don't throw f) [ f throw ] catch  ! returns f, bad! use recover or cleanup instead</lang>

Forth

Forth's exception mechanism is, like most things in Forth, very simple but powerful. CATCH captures the data and return stack pointers, then executes an execution token. THROW conditionally throws a value up to the most recent CATCH, restoring the stack pointers.

Throw Exceptions

<lang forth>: f ( -- ) 1 throw ." f " ; \ will throw a "1"

g ( -- ) 0 throw ." g " ; \ does not throw</lang>

Catch Exceptions

<lang forth>: report ( n -- ) ?dup if ." caught " . else ." no throw" then ;

test ( -- )
 ['] f catch report
 ['] g catch report ;</lang>

test example. (Output shown in bold) <lang forth>cr test caught 1 g no throw ok</lang>

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: <lang forth>10 ['] myfun catch if drop then</lang>

Haskell

Exceptions can be implemented using monads; no special syntax is necessary.[1] In GHC, specialized functionality for exceptions are provided by the Control.Exception 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.

Throw exceptions

In the context of the IO monad, use "throwIO" to throw exceptions; the expression will return any type: <lang haskell>do {- ... -}

  throwIO SomeException</lang>

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

To throw a user-defined exception, use "throwDyn": <lang haskell>if condition then 3 else throwDyn myException</lang>

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: <lang haskell>do

 {- do IO computations here -}

`catch` \ex -> do

 {- handle exception "ex" here -}</lang>

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

To catch a user-defined exception, use "catchDyn": <lang haskell>do

 {- do IO computations here -}

`catchDyn` \ex -> do

 {- handle exception "ex" here -}</lang>

J

Tacit

Program u :: v executes u and provides its result as output unless an error occurs. In case of error, the result of v is provided instead.

Explicit

An exception in an explicit definition can be detected with try. and catcht. and can be thrown with throw. as seen below.

<lang j> pickyPicky =: verb define

    if. y-:'bad argument' do.
       throw.
    else.
       'thanks!'
    end.
  )
  
  tryThis  =: verb define
    try.
       pickyPicky y
    catcht.
       'Uh oh!'
    end.
  )
  tryThis 'bad argument'

Uh oh!</lang>

Java

An exception needs to extend the Exception type.

Defining exceptions

<lang java>//Checked exception public class MyException extends Exception {

  //Put specific info in here

}

//Unchecked exception public class MyRuntimeException extends RuntimeException {}</lang>

Throw exceptions

<lang java>public void fooChecked() throws MyException {

  throw new MyException();

}

public void fooUnchecked() {

  throw new MyRuntimeException();

}</lang>

Catching exceptions

<lang java>try {

  fooChecked();

} catch(MyException exc) {

  //Catch only your specified type of exception

} catch(Exception exc) {

  //Catch any non-system error exception

} catch(Throwable exc) {

  //Catch everything including system errors (not recommended)

} finally {

  //This code is always executed after exiting the try block

}</lang>

JavaScript

Throwing exceptions

<lang javascript>function doStuff() {

 throw new Error('Not implemented!');

}</lang>

Catching exceptions

<lang javascript>try {

 element.attachEvent('onclick', doStuff);

} catch(e if e instanceof TypeError) {

 element.addEventListener('click', doStuff, false);

} finally {

 eventSetup = true;

}</lang>

Works with: UCB Logo

<lang logo>to div.checked :a :b

 if :b = 0 [(throw "divzero 0)]
 output :a / :b

end to div.safely :a :b

 output catch "divzero [div.checked :a :b]

end</lang> There are also some predefined exceptions:

  • throw "toplevel returns to the interactive prompt if uncaught (like control-C)
  • (throw "error [message]) prints a message like a primitive, bypassing normal catch output
  • throw "system immediately exits Logo to the shell
  • catch "error will catch any thrown error instead of printing an error message

Make

In make, an exception is caused when a rule returns a non-zero status i.e the below will fail as false returns 1, (thus raising exception)

fail.mk

<lang make>all:

    false</lang>

Using -@ to ignore the exception.

catch.mk

<lang make>all:

   -@make -f fail.mk</lang>

Using explicit exit 0 to ignore the exception.

catch.mk

<lang make>all:

   make -f fail.mk; exit 0</lang>

Modula-3

Defining exceptions

Exceptions can only be declared at the "top-level" of a module or interface. Arguments are optional. <lang modula3>EXCEPTION EndOfFile; EXCEPTION Error(TEXT);</lang>

Throw exceptions

Exceptions can be bound to procedures using RAISES: <lang modula3>PROCEDURE Foo() RAISES { EndOfFile } =

 ...
 RAISE EndOfFile;
 ...</lang>

Catching exceptions

<lang modula3>TRY

 Foo();

EXCEPT | EndOfFile => HandleFoo(); END;</lang>

Modula-3 also has a FINALLY keyword: <lang modula3>TRY

 Foo();

FINALLY

 CleanupFoo(); (* always executed *)

END;</lang>


MOO

Throw exceptions

Values can be raised to exceptions using raise(): <lang moo>raise(E_PERM);</lang>

Catching exceptions

<lang moo>try

 this:foo();

except e (ANY)

 this:bar(e);

endtry</lang>

MOO also has a finally statement: <lang moo>try

 this:foo();

finally

 this:bar();

endtry</lang>

Shorthand

<lang moo>`this:foo()!ANY=>this:bar()';</lang>

Objective-C

Defining exceptions

Exceptions can be any Objective-C object, though they are usually instances of NSException. You can create a subclass of NSException if necessary: <lang objc>@interface MyException : NSException {

 //Put specific info in here

} @end</lang>

Throw exceptions

<lang objc>- (void)foo {

 @throw [NSException exceptionWithName:@"TerribleException"
                                reason:@"OMGWTFBBQ111!1"  userInfo:nil];

}</lang>

Catching exceptions

<lang objc>@try {

 [self foo];

} @catch (MyException *exc) {

 //Catch only your specified type of exception

} @catch (NSException *exc) {

 //Catch any NSException or subclass
 NSLog(@"caught exception named %@, with reason: %@", [exc name], [exc reason]);  

} @catch (id exc) {

 //Catch any kind of object

} @finally {

 //This code is always executed after exiting the try block

}</lang>

OCaml

Defining exceptions

Like constructors, exceptions may or may not have an argument: <lang ocaml>exception My_Exception;; exception Another_Exception of string;;</lang>

Throw exceptions

Throw exceptions with the "raise" function; the expression will match any type: <lang ocaml>let foo x =

 match x with
   1 -> raise My_Exception
 | 2 -> raise (Another_Exception "hi mom")
 | _ -> 5
</lang>

Catching exceptions

The "with" syntax pattern-matches on the exception type and argument: <lang ocaml>try

 string_of_int (foo 2)

with

 My_Exception        -> "got my exception"

| Another_Exception s -> s | _ -> "unknown exception"</lang>

Perl

<lang perl># throw an exception die "Danger, danger, Will Robinson!";

  1. catch an exception and show it

eval {

   die "this could go wrong mightily";

}; print $@ if $@;

  1. rethrow

die $@;</lang>

See http://perldoc.perl.org/perlvar.html#%24EVAL_ERROR for the meaning of the special variable $@. See http://search.cpan.org/dist/Error for advanced object based-exception handling.

PHP

Works with: PHP version 5.0+

Exceptions were not available prior to PHP 5.0

Define exceptions

<lang php>class MyException extends Exception {

   //  Custom exception attributes & methods

}</lang>

Throwing exceptions

<lang php>function throwsException() {

   throw new Exception('Exception message');

}</lang>

Catching Exceptions

<lang php>try {

   throwsException();

} catch (Exception $e) {

   echo 'Caught exception: ' . $e->getMessage();

}</lang>

Pop11

Throwing exceptions

<lang pop11>define throw_exception();

  throw([my_exception my_data]);

enddefine;</lang>

Catching exceptions

<lang pop11>define main();

  vars cargo;
  define catcher();
     ;;; print exception data
     cargo =>
  enddefine;
  catch(throw_exception, catcher, [my_exception ?cargo]);

enddefine;

main();</lang>

Python

Defining an exception

<lang python>import exceptions class SillyError(exceptions.Exception):

   def __init__(self,args=None):
        self.args=args</lang>

Note: In most cases new exceptions are defined simply using the pass statement. For example:

<lang python>class MyInvalidArgument(ValueError):

  pass</lang>

This example makes "MyInvalidArgument" an type of ValueError (one of the built-in exceptions). It's simply declared as a subclass of the existing exception and no over-riding is necessary. (An except clause for ValueError would catch MyInvalidArgument exceptions ... but one's code could insert a more specific exception handler for the more specific type of exception).

Throwing an exception

Works with: Python version 2.x and 3.x

Creating an exception using the default constructor of an exception class: <lang python>def spam():

   raise SillyError # equivalent to raise SillyError()</lang>
Works with: Python version 2.5

Passing an argument to the constructor of an exception class: <lang python>def spam():

   raise SillyError, 'egg' # equivalent to raise SillyError('egg')</lang>

The above syntax is removed in Python 3.0; but the following syntax works in Python 2.x and 3.x, so should be preferred.

Works with: Python version 2.x and 3.x

<lang python>def spam():

   raise SillyError('egg')</lang>

Handling an exception

Works with: Python version 2.5

try-except-else-finally

<lang python>try:

  foo()

except SillyError, se:

  print se.args
  bar()

else:

  # no exception occurred
  quux()

finally:

  baz()</lang>

Before Python 2.5 it was not possible to use finally and except together. (It was necessary to nest a separate try...except block inside of your try...finally block).

Works with: Python version 3.0

Note: Python3 will change the syntax of except slightly, but in a way that is not backwards compatible. In Python 2.x and earlier the except statement could list a single exception or a tuple/list of exceptions and optionally a name to which the exception object will be bound. In the old versions the exception's name followed a comma (as in the foregoing example). In Python3 the syntax will become: except Exception1 [,Exception2 ...] as ExceptionName <lang python>try:

  foo()

except SillyError as se:

  print(se.args)
  bar()

else:

  # no exception occurred
  quux()

finally:

  baz()</lang>

Raven

<lang raven>42 as custom_error

define foo

   custom_error throw

try

   foo

catch

   custom_error =
   if  'oops' print</lang>

Ruby

Defining an exception

<lang ruby>class SillyError < Exception

   def initialize(args = nil)
        @args = args
   end

end</lang>

Note: Often new exceptions are defined simply with no body. For example:

<lang ruby>class MyInvalidArgument < ArgumentError end</lang>

This example makes "MyInvalidArgument" an type of ArgumentError (one of the built-in exceptions). It's simply declared as a subclass of the existing exception and no over-riding is necessary. (A rescue clause for ArgumentError would catch MyInvalidArgument exceptions ... but one's code could insert a more specific exception handler for the more specific type of exception).

Throwing an exception

<lang ruby>def spam

   raise SillyError, 'egg'

end</lang>

Handling an exception

rescue/else/ensure

<lang ruby>begin

   foo

rescue SillyError, se

   print se.args
   bar()

else

   # no exception occurred
   quux

ensure

   baz

end</lang>

The "rescue" clause is like the "catch" clause in other languages. The "ensure" clause is like the "finally" clause in other languages.

Catch/Throw

Ruby has a separate exception-like system that is meant to be used to exit out of deep executions that are not errors.

<lang ruby>def foo

   throw :done

end

catch :done do

   foo

end</lang>

You can only "throw" and "catch" symbols. Like exceptions, the throw can be made from a function defined elsewhere from the catch block.

Slate

Handling Exceptions

<lang slate>se@(SceneElement traits) doWithRestart: block [

 block handlingCases: {Abort -> [| :_ | ^ Nil]}

].</lang>

Define Exceptions

<lang slate>conditions define: #Abort &parents: {Restart}. "An Abort is a Restart which exits the computation, unwinding the stack."

_@lobby abort [

 Abort signal

]. _@(Abort traits) describeOn: console [

 console ; 'Abort evaluation of expression\n'

].

"This will call:" c@(Condition traits) signal "Signalling a Condition." [

 c tryHandlers

].</lang>

Throwing Exceptions

<lang slate>(fileName endsWith: '.image') ifTrue: [error: 'Image filename specified where Slate source expected. Make sure you run slate with the -i flag to specify an image.'].</lang>

Standard ML

Define Exceptions

<lang sml>exception MyException; exception MyDataException of int; (* can be any first-class type, not just int *)</lang>

Throw Exceptions

<lang sml>fun f() = raise MyException; fun g() = raise MyDataException 22;</lang>

Catch Exceptions

<lang sml>val x = f() handle MyException => 22; val y = f() handle MyDataException x => x;</lang>

Tcl

<lang tcl>package require Tcl 8.5

  1. Throw

proc e {args} {

   error "error message" "error message for stack trace" {errorCode list}

}

  1. Catch and rethrow

proc f {} {

   if {[catch {e 1 2 3 4} errMsg options] != 0} {
       return -options $options $errMsg 
   }

}

f</lang> This creates the stack trace

error message for stack trace
    (procedure "e" line 1)
    invoked from within
"e 1 2 3 4"
    (procedure "f" line 2)
    invoked from within
"f"

Ursala

In this program fragment, a function named thrower returns the string 'success' if its argument is non-empty, but otherwise raises an exception with the diagnostic message 'epic fail'. (The diagnostic message can also be made to depend on the input.) <lang Ursala>#import std

thrower = ~&?/'success'! -[epic fail]-!%

catcher = guard(thrower,---[someone failed]-)</lang>

If the exception is not caught, the program terminates immediately and the diagnostic is written to stderr. Alternatively, a calling function or any caller thereof can be defined to catch an exception as shown. The exception handler may inspect and arbitrarily modify the diagnostic message, but normal execution may not be resumed. In this example, the exception handler appends some additional verbiage to the message.

V

throwing exceptions <lang v>[myproc

 ['new error' 1 2 3] throw
 'should not come here' puts

].</lang>

catching them

<lang v>[myproc] [puts] catch =[new error 1 2 3]</lang>

Visual Basic .NET

Defining exceptions

<lang vbnet>Class MyException

 Inherits Exception
 'data with info about exception

End Class</lang>

Throw exceptions

<lang vbnet>Sub foo()

   Throw New MyException

End Sub</lang>

Catching exceptions

<lang vbnet>Sub bar()

   Try
       foo()
   Catch e As MyException When e.Data.Contains("Foo")
       ' handle exceptions of type MyException when the exception contains specific data
   Catch e As MyException
       ' handle exceptions of type MyException and derived exceptions
   Catch e As Exception
       ' handle any type of exception not handled by above catches
   Finally
       'code here occurs whether or not there was an exception
   End Try

End Sub</lang>