Exceptions: Difference between revisions

m
Fixed lang tags.
m (Fixed lang tags.)
Line 6:
=={{header|Ada}}==
===Define an exception===
<lang ada>Foo_Error : exception;</lang>
Foo_Error : exception;
</lang>
===Raise an exception===
<lang ada>procedure Foo is
procedure Foo is
begin
raise Foo_Error;
end Foo;</lang>
</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>
</lang>
===Handle an exception===
<lang ada>procedure Call_Foo is
procedure Call_Foo is
begin
Foo;
Line 35 ⟶ 28:
when others =>
... -- this catches all other exceptions
end Call_Foo;</lang>
</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;
<lang ada>
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Text_IO; use Ada.Text_IO;
 
Line 51 ⟶ 42:
when Error : others =>
Put_Line ("Something is wrong here" & Exception_Information (Error));
end Main;</lang>
</lang>
=={{header|ALGOL 68}}==
===Define an exception===
<lang algol68># a user defined object #
<pre>
# 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>
 
</pre>
===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);
Line 73 ⟶ 59:
# now raise example foo event #
IF NOT (foo event mended OF foo proxy)(foo proxy) THEN undefined # trace back # FI
OD;</lang>
 
</pre>
Re-raising once caught exception:
<lang algol68>...
<pre>
...
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>
</pre>
===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
TRUE # continue #
Line 92 ⟶ 73:
except foo event
FALSE # OR fall back to default event routine #
FI</lang>
</pre>
===Standard Prelude "on event" routines===
ALGOL 68 uses event routines extensively in the "standard transput"
Line 123 ⟶ 103:
=={{header|AppleScript}}==
===try===
<lang applescript>try
try
set num to 1 / 0
--do something that might throw an error
end try</lang>
 
===try-on error===
<lang applescript>try
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>
=={{header|AutoHotkey}}==
<lang AutoHotkey>foo()
foo()
If ErrorLevel
Msgbox calling foo failed with: %ErrorLevel%
Line 152 ⟶ 131:
ErrorLevel = foo_error
Return
}</lang>
}
 
</lang>
 
=={{header|C}}==
Line 162 ⟶ 139:
===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>
 
=={{header|C++}}==
Line 195 ⟶ 172:
 
===Defining exceptions===
<lang cpp>struct MyException
struct MyException
{
// 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>.
 
<lang cpp>#include <exception>
#include <exception>
struct MyException: std::exception
{
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.
 
===Throw exceptions===
<lang cpp>// this function can throw any type of exception
<lang cpp>
// this function can throw any type of exception
void foo()
{
Line 232 ⟶ 204:
{
throw MyException();
}</lang>
}
</lang>
 
===Catching exceptions===
<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 #}}==
{{works with|Visual Studio|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>
}
 
 
Line 289 ⟶ 258:
inside &lt;cfscript&gt;:
 
<lang cfm>try {
foo();
} catch (Any e) {
// handle exception e
}</lang>
}
 
otherwise:
<lang &lt;cfm><cftry&gt;>
&lt;<cfcatch type="Database|..."&gt;>
&lt;</cfcatch&gt;>
&lt;</cftry&gt;></lang>
 
=={{header|Common Lisp}}==
Line 367 ⟶ 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.
 
<lang e>def nameOf(arg :int) {
def nameOf(arg :int) {
if (arg == 43) {
return "Bob"
Line 417 ⟶ 385:
return ["notok", exceptionObj]
}
}</lang>
}
</lang>
 
<lang e>? catching(42)
Line 453 ⟶ 420:
=={{header|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>
 
=={{header|Forth}}==
Line 480 ⟶ 447:
 
===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>
 
=={{header|Haskell}}==
Line 503 ⟶ 470:
===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
{- 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
{- do IO computations here -}
`catchDyn` \ex -> do
{- handle exception "ex" here -}</lang>
 
=={{header|J}}==
Line 538 ⟶ 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.
 
<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>
 
=={{header|Java}}==
Line 561 ⟶ 528:
 
===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>
}
 
=={{header|JavaScript}}==
Line 599 ⟶ 566:
===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>
}
 
=={{header|Logo}}==
{{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)
Line 636 ⟶ 603:
fail.mk
 
<lang make>all:
false</lang>
 
Using -@ to ignore the exception.
Line 643 ⟶ 610:
catch.mk
 
<lang make>all:
-@make -f fail.mk</lang>
 
Using explicit exit 0 to ignore the exception.
Line 650 ⟶ 617:
catch.mk
 
<lang make>all:
make -f fail.mk; exit 0</lang>
 
=={{header|Modula-3}}==
Line 665 ⟶ 632:
...
RAISE EndOfFile;
...</lang>
</lang>
 
===Catching exceptions===
Line 680 ⟶ 646:
FINALLY
CleanupFoo(); (* always executed *)
END;</lang>
</lang>
 
 
Line 698 ⟶ 663:
 
MOO also has a finally statement:
<lang modula3moo>try
this:foo();
finally
Line 744 ⟶ 709:
===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
try
string_of_int (foo 2)
with
My_Exception -> "got my exception"
| Another_Exception s -> s
| _ -> "unknown exception"</lang>
 
=={{header|Perl}}==
Line 787 ⟶ 752:
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>
}
 
=={{header|Pop11}}==
Line 808 ⟶ 773:
===Throwing exceptions===
 
<lang pop11>define throw_exception();
<pre>
define throw_exception();
throw([my_exception my_data]);
enddefine;</lang>
</pre>
 
===Catching exceptions===
 
<lang pop11>define main();
<pre>
define main();
vars cargo;
define catcher();
Line 826 ⟶ 788:
enddefine;
 
main();</lang>
</pre>
 
=={{header|Python}}==
Line 833 ⟶ 794:
===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>
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).
Line 896 ⟶ 855:
=={{header|Raven}}==
 
<lang raven>42 as custom_error
 
define foo
custom_error throw
 
try
foo
catch
custom_error =
if 'oops' print</lang>
 
=={{header|Ruby}}==
Line 951 ⟶ 910:
Ruby has a separate exception-like system that is meant to be used to exit out of deep executions that are not errors.
 
<lang pythonruby>def foo
throw :done
end
Line 965 ⟶ 924:
===Handling Exceptions===
 
<lang slate>se@(SceneElement traits) doWithRestart: block
se@(SceneElement traits) doWithRestart: block
[
block handlingCases: {Abort -> [| :_ | ^ Nil]}
].</lang>
 
</lang>
 
===Define Exceptions===
 
<lang slate>conditions define: #Abort &parents: {Restart}.
conditions define: #Abort &parents: {Restart}.
"An Abort is a Restart which exits the computation, unwinding the stack."
 
Line 993 ⟶ 948:
[
c tryHandlers
].</lang>
 
</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>
<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}}==
===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>
 
=={{header|Tcl}}==
Line 1,063 ⟶ 1,013:
 
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>
 
=={{header|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>
 
{{omit from|M4}}
Anonymous user