Exceptions: Difference between revisions
Content deleted Content added
→Go: New section |
Changed secondary headers into just bold text to shorten the contents |
||
Line 5: | Line 5: | ||
Cf. [[Exceptions Through Nested Calls]] |
Cf. [[Exceptions Through Nested Calls]] |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
'''Define an exception''' |
|||
<lang ada>Foo_Error : exception;</lang> |
<lang ada>Foo_Error : exception;</lang> |
||
'''Raise an exception''' |
|||
<lang ada>procedure Foo is |
<lang ada>procedure Foo is |
||
begin |
begin |
||
Line 19: | Line 21: | ||
raise; -- continue propagation of |
raise; -- continue propagation of |
||
end if;</lang> |
end if;</lang> |
||
'''Handle an exception''' |
|||
<lang ada>procedure Call_Foo is |
<lang ada>procedure Call_Foo is |
||
begin |
begin |
||
Line 29: | Line 32: | ||
... -- this catches all other exceptions |
... -- this catches all other exceptions |
||
end Call_Foo;</lang> |
end Call_Foo;</lang> |
||
'''Ada.Exceptions'''<br> |
|||
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; |
||
Line 46: | Line 50: | ||
=={{header|Aikido}}== |
=={{header|Aikido}}== |
||
Aikido provides <code>try</code>, <code>catch</code> and <code>throw</code> statements. |
Aikido provides <code>try</code>, <code>catch</code> and <code>throw</code> statements. |
||
'''Catching exceptions'''<br> |
|||
There is one <code>catch</code> clause per <code>try</code> statement. The variable caught is whatever is thrown. It does not have to be a particular type, although there is a <code>System.Exception</code> class defined for system exceptions. |
There is one <code>catch</code> clause per <code>try</code> statement. The variable caught is whatever is thrown. It does not have to be a particular type, although there is a <code>System.Exception</code> class defined for system exceptions. |
||
<lang aikido> |
<lang aikido> |
||
Line 58: | Line 63: | ||
</lang> |
</lang> |
||
'''Throwing exceptions'''<br> |
|||
You can throw any value. |
You can throw any value. |
||
<lang aikido> |
<lang aikido> |
||
Line 73: | Line 78: | ||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
'''Define an exception''' |
|||
<lang algol68># a user defined object # |
<lang algol68># a user defined object # |
||
MODE OBJECTFOO = STRUCT ( PROC (REF OBJECTFOO)BOOL foo event mended, ... ); |
MODE OBJECTFOO = STRUCT ( PROC (REF OBJECTFOO)BOOL foo event mended, ... ); |
||
Line 80: | Line 86: | ||
foo event mended OF foo := foo event |
foo event mended OF foo := foo event |
||
);</lang> |
);</lang> |
||
'''Raise an exception''' |
|||
<lang algol68>OBJECTFOO foo proxy := foo base; # event routines are specific to an foo # |
<lang algol68>OBJECTFOO foo proxy := foo base; # event routines are specific to an foo # |
||
Line 95: | Line 102: | ||
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</lang> |
FI</lang> |
||
'''Handle an exception''' |
|||
<lang algol68>PROC raise foo event(REF OBJECTFOO foo)BOOL: |
<lang algol68>PROC raise foo event(REF OBJECTFOO foo)BOOL: |
||
IF mend foo(foo) THEN |
IF mend foo(foo) THEN |
||
Line 103: | Line 111: | ||
FALSE # OR fall back to default event routine # |
FALSE # OR fall back to default event routine # |
||
FI</lang> |
FI</lang> |
||
'''Standard Prelude "on event" routines'''<br> |
|||
ALGOL 68 uses event routines extensively in the "standard transput" |
ALGOL 68 uses event routines extensively in the "standard transput" |
||
(stdio) to manage the various events that arise when data is read |
(stdio) to manage the various events that arise when data is read |
||
Line 131: | Line 140: | ||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
===try=== |
|||
'''try''' |
|||
<lang applescript>try |
<lang applescript>try |
||
set num to 1 / 0 |
set num to 1 / 0 |
||
Line 137: | Line 147: | ||
end try</lang> |
end try</lang> |
||
'''try-on error''' |
|||
<lang applescript>try |
<lang applescript>try |
||
set num to 1 / 0 |
set num to 1 / 0 |
||
Line 146: | Line 156: | ||
end try</lang> |
end try</lang> |
||
'''error''' |
|||
<lang applescript>error "Error message." number 2000</lang> |
<lang applescript>error "Error message." number 2000</lang> |
||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
Line 166: | Line 176: | ||
The setjmp()/longjmp() functions in the C standard library header <setjmp.h> are typically used for exception handling. |
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> |
<lang c>#include <setjmp.h> |
||
Line 203: | Line 213: | ||
The exception can be of any type, this includes int's, other primitives, as well as objects. |
The exception can be of any type, this includes int's, other primitives, as well as objects. |
||
'''Defining exceptions''' |
|||
<lang cpp>struct MyException |
<lang cpp>struct MyException |
||
{ |
{ |
||
Line 219: | Line 229: | ||
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''' |
|||
<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 238: | Line 248: | ||
}</lang> |
}</lang> |
||
'''Catching exceptions''' |
|||
<lang cpp>try { |
<lang cpp>try { |
||
foo(); |
foo(); |
||
Line 260: | Line 270: | ||
{{works with|Visual Studio|2005}} |
{{works with|Visual Studio|2005}} |
||
'''Defining exceptions''' |
|||
<lang csharp>public class MyException : Exception |
<lang csharp>public class MyException : Exception |
||
{ |
{ |
||
Line 266: | Line 276: | ||
};</lang> |
};</lang> |
||
'''Throw exceptions''' |
|||
<lang csharp>void foo() |
<lang csharp>void foo() |
||
{ |
{ |
||
Line 272: | Line 282: | ||
}</lang> |
}</lang> |
||
'''Catching exceptions''' |
|||
<lang csharp>try { |
<lang csharp>try { |
||
foo(); |
foo(); |
||
Line 287: | Line 297: | ||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
'''Catch Exceptions'''<br> |
|||
inside <cfscript>: |
inside <cfscript>: |
||
Line 326: | Line 337: | ||
=={{header|D}}== |
=={{header|D}}== |
||
'''Throw Exceptions''' |
|||
<lang d>void test() { |
<lang d>void test() { |
||
throw new Exception("Sample Exception"); |
throw new Exception("Sample Exception"); |
||
}</lang> |
}</lang> |
||
'''Catch Exceptions''' |
|||
<lang d>void test2() { |
<lang d>void test2() { |
||
try test(); |
try test(); |
||
Line 339: | Line 351: | ||
In debug mode, stack traces can be generated via an external package, but the standard library does not support it by default. |
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() { |
<lang d>void test3() { |
||
try test2(); |
try test2(); |
||
Line 354: | Line 366: | ||
=={{header|E}}== |
=={{header|E}}== |
||
'''Exceptions''' |
|||
An exception ''object'' describes what the problem is and has nothing to do with control flow. |
An exception ''object'' describes what the problem is and has nothing to do with control flow. |
||
Line 364: | Line 376: | ||
There are two control flow constructs used with exceptions: throw and eject. |
There are two control flow constructs used with exceptions: throw and eject. |
||
'''Throw and catch''' |
|||
<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. |
||
Line 395: | Line 407: | ||
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. |
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. |
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. |
||
Line 451: | Line 463: | ||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
'''Throw Exceptions''' |
|||
<lang factor>"Install Linux, Problem Solved" throw |
<lang factor>"Install Linux, Problem Solved" throw |
||
Line 461: | Line 474: | ||
velociraptor</lang> |
velociraptor</lang> |
||
'''Catch Exceptions''' |
|||
<lang factor>! Preferred exception handling |
<lang factor>! Preferred exception handling |
||
: try-foo |
: try-foo |
||
Line 478: | Line 491: | ||
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. |
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" |
<lang forth>: f ( -- ) 1 throw ." f " ; \ will throw a "1" |
||
: g ( -- ) 0 throw ." g " ; \ does not throw</lang> |
: g ( -- ) 0 throw ." g " ; \ does not throw</lang> |
||
'''Catch Exceptions''' |
|||
<lang forth>: report ( n -- ) ?dup if ." caught " . else ." no throw" then ; |
<lang forth>: report ( n -- ) ?dup if ." caught " . else ." no throw" then ; |
||
: test ( -- ) |
: test ( -- ) |
||
Line 516: | Line 529: | ||
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 <tt>Control.Exception</tt> module. |
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 <tt>Control.Exception</tt> module. |
||
'''Defining exceptions'''<br> |
|||
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. --> |
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'''<br> |
|||
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: |
||
<lang haskell>do {- ... -} |
<lang haskell>do {- ... -} |
||
Line 532: | Line 545: | ||
else throwDyn myException</lang> |
else throwDyn myException</lang> |
||
'''Catching exceptions'''<br> |
|||
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: |
||
Line 550: | Line 563: | ||
=={{header|J}}== |
=={{header|J}}== |
||
'''Tacit'''<br> |
|||
Program<tt> u :: v </tt>executes <tt>u</tt> and provides its result as output unless an error occurs. In case of error, the result of <tt>v</tt> is provided instead.<br> |
Program<tt> u :: v </tt>executes <tt>u</tt> and provides its result as output unless an error occurs. In case of error, the result of <tt>v</tt> is provided instead.<br> |
||
'''Explicit'''<br> |
|||
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. |
||
Line 578: | Line 591: | ||
An exception needs to extend the Exception type. |
An exception needs to extend the Exception type. |
||
'''Defining exceptions''' |
|||
<lang java>//Checked exception |
<lang java>//Checked exception |
||
public class MyException extends Exception { |
public class MyException extends Exception { |
||
Line 587: | Line 600: | ||
public class MyRuntimeException extends RuntimeException {}</lang> |
public class MyRuntimeException extends RuntimeException {}</lang> |
||
'''Throw exceptions''' |
|||
<lang java>public void fooChecked() throws MyException { |
<lang java>public void fooChecked() throws MyException { |
||
throw new MyException(); |
throw new MyException(); |
||
Line 596: | Line 609: | ||
}</lang> |
}</lang> |
||
'''Catching exceptions''' |
|||
<lang java>try { |
<lang java>try { |
||
fooChecked(); |
fooChecked(); |
||
Line 615: | Line 628: | ||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
'''Throwing exceptions''' |
|||
<lang javascript>function doStuff() { |
<lang javascript>function doStuff() { |
||
Line 621: | Line 634: | ||
}</lang> |
}</lang> |
||
'''Catching exceptions''' |
|||
<lang javascript>try { |
<lang javascript>try { |
||
Line 673: | Line 686: | ||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
'''Defining exceptions'''<br> |
|||
Exceptions can only be declared at the "top-level" of a module or interface. Arguments are optional. |
Exceptions can only be declared at the "top-level" of a module or interface. Arguments are optional. |
||
<lang modula3>EXCEPTION EndOfFile; |
<lang modula3>EXCEPTION EndOfFile; |
||
EXCEPTION Error(TEXT);</lang> |
EXCEPTION Error(TEXT);</lang> |
||
'''Throw exceptions'''<br> |
|||
Exceptions can be bound to procedures using RAISES: |
Exceptions can be bound to procedures using RAISES: |
||
<lang modula3>PROCEDURE Foo() RAISES { EndOfFile } = |
<lang modula3>PROCEDURE Foo() RAISES { EndOfFile } = |
||
Line 685: | Line 698: | ||
...</lang> |
...</lang> |
||
'''Catching exceptions''' |
|||
<lang modula3>TRY |
<lang modula3>TRY |
||
Foo(); |
Foo(); |
||
Line 702: | Line 715: | ||
=={{header|MOO}}== |
=={{header|MOO}}== |
||
'''Throw exceptions'''<br> |
|||
Values can be raised to exceptions using raise(): |
Values can be raised to exceptions using raise(): |
||
<lang moo>raise(E_PERM);</lang> |
<lang moo>raise(E_PERM);</lang> |
||
'''Catching exceptions''' |
|||
<lang moo>try |
<lang moo>try |
||
this:foo(); |
this:foo(); |
||
Line 720: | Line 733: | ||
endtry</lang> |
endtry</lang> |
||
'''Shorthand''' |
|||
<lang moo>`this:foo()!ANY=>this:bar()';</lang> |
<lang moo>`this:foo()!ANY=>this:bar()';</lang> |
||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
'''Defining exceptions'''<br> |
|||
Exceptions can be any Objective-C object, though they are usually instances of <code>NSException</code>. You can create a subclass of NSException if necessary: |
Exceptions can be any Objective-C object, though they are usually instances of <code>NSException</code>. You can create a subclass of NSException if necessary: |
||
<lang objc>@interface MyException : NSException { |
<lang objc>@interface MyException : NSException { |
||
Line 732: | Line 745: | ||
@end</lang> |
@end</lang> |
||
'''Throw exceptions''' |
|||
<lang objc>- (void)foo { |
<lang objc>- (void)foo { |
||
@throw [NSException exceptionWithName:@"TerribleException" |
@throw [NSException exceptionWithName:@"TerribleException" |
||
Line 738: | Line 751: | ||
}</lang> |
}</lang> |
||
'''Catching exceptions''' |
|||
<lang objc>@try { |
<lang objc>@try { |
||
[self foo]; |
[self foo]; |
||
Line 758: | Line 771: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
'''Defining exceptions'''<br> |
|||
Like constructors, exceptions may or may not have an argument: |
Like constructors, exceptions may or may not have an argument: |
||
<lang ocaml>exception My_Exception;; |
<lang ocaml>exception My_Exception;; |
||
exception Another_Exception of string;;</lang> |
exception Another_Exception of string;;</lang> |
||
'''Throw exceptions'''<br> |
|||
Throw exceptions with the "raise" function; the expression will match any type: |
Throw exceptions with the "raise" function; the expression will match any type: |
||
<lang ocaml>let foo x = |
<lang ocaml>let foo x = |
||
Line 772: | Line 785: | ||
;;</lang> |
;;</lang> |
||
'''Catching exceptions'''<br> |
|||
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 |
<lang ocaml>try |
||
Line 782: | Line 795: | ||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
⚫ | |||
'''Throw exceptions'''<br> |
|||
Any value can be thrown as an exception. Typically record values are used. |
Any value can be thrown as an exception. Typically record values are used. |
||
<lang oz>raise sillyError end |
<lang oz>raise sillyError end |
||
Line 797: | Line 811: | ||
See also: [http://www.mozart-oz.org/documentation/base/exception.html Exceptions] in the Oz documentation. |
See also: [http://www.mozart-oz.org/documentation/base/exception.html Exceptions] in the Oz documentation. |
||
'''Catching exceptions'''<br> |
|||
Exception are caught with pattern matching. Ellipsis indicating additional optional fields are often useful here. |
Exception are caught with pattern matching. Ellipsis indicating additional optional fields are often useful here. |
||
<lang oz>try |
<lang oz>try |
||
Line 812: | Line 826: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
'''Using eval'''<br> |
|||
Expeptions using the core [http://perldoc.perl.org/functions/eval.html eval] function: |
Expeptions using the core [http://perldoc.perl.org/functions/eval.html eval] function: |
||
Line 829: | Line 844: | ||
See http://perldoc.perl.org/perlvar.html#%24EVAL_ERROR for the meaning of the special variable <tt>$@</tt>. See http://search.cpan.org/dist/Error for advanced object based-exception handling. |
See http://perldoc.perl.org/perlvar.html#%24EVAL_ERROR for the meaning of the special variable <tt>$@</tt>. See http://search.cpan.org/dist/Error for advanced object based-exception handling. |
||
'''Using Try::Tiny'''<br> |
|||
The same using the [http://search.cpan.org/perldoc?Try::Tiny Try::Tiny] module: |
The same using the [http://search.cpan.org/perldoc?Try::Tiny Try::Tiny] module: |
||
Line 843: | Line 858: | ||
die $_;</lang> |
die $_;</lang> |
||
'''Other styles'''<br> |
|||
More complicated exception handling can be achieved in Perl using [http://search.cpan.org/perldoc?TryCatch TryCatch] or [http://search.cpan.org/perldoc?Exception::Class Exception::Class] modules. |
More complicated exception handling can be achieved in Perl using [http://search.cpan.org/perldoc?TryCatch TryCatch] or [http://search.cpan.org/perldoc?Exception::Class Exception::Class] modules. |
||
Line 851: | Line 866: | ||
Exceptions were not available prior to PHP 5.0 |
Exceptions were not available prior to PHP 5.0 |
||
'''Define exceptions''' |
|||
<lang php>class MyException extends Exception |
<lang php>class MyException extends Exception |
||
{ |
{ |
||
Line 857: | Line 873: | ||
}</lang> |
}</lang> |
||
'''Throwing exceptions''' |
|||
<lang php>function throwsException() |
<lang php>function throwsException() |
||
{ |
{ |
||
throw new Exception('Exception message'); |
throw new Exception('Exception message'); |
||
}</lang> |
}</lang> |
||
'''Catching Exceptions''' |
|||
<lang php>try { |
<lang php>try { |
||
throwsException(); |
throwsException(); |
||
Line 899: | Line 916: | ||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
'''Throwing exceptions''' |
|||
<lang pop11>define throw_exception(); |
<lang pop11>define throw_exception(); |
||
Line 905: | Line 922: | ||
enddefine;</lang> |
enddefine;</lang> |
||
'''Catching exceptions''' |
|||
<lang pop11>define main(); |
<lang pop11>define main(); |
||
Line 920: | Line 937: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
'''Defining an exception''' |
|||
<lang python>import exceptions |
<lang python>import exceptions |
||
Line 934: | Line 951: | ||
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). |
||
'''Throwing an exception'''<br> |
|||
{{works with|Python|2.x and 3.x}} |
{{works with|Python|2.x and 3.x}} |
||
Creating an exception using the default constructor of an exception class: |
Creating an exception using the default constructor of an exception class: |
||
<lang python>def spam(): |
<lang python>def spam(): |
||
Line 941: | Line 959: | ||
{{works with|Python|2.5}} |
{{works with|Python|2.5}} |
||
Passing an argument to the constructor of an exception class: |
Passing an argument to the constructor of an exception class: |
||
<lang python>def spam(): |
<lang python>def spam(): |
||
Line 950: | Line 969: | ||
raise SillyError('egg')</lang> |
raise SillyError('egg')</lang> |
||
'''Handling an exception'''<br> |
|||
{{works with|Python|2.5}} |
{{works with|Python|2.5}} |
||
Line 969: | Line 988: | ||
{{works with|Python|3.0}} |
{{works with|Python|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'' |
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: |
<lang python>try: |
||
Line 996: | Line 1,016: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
'''Defining an exception''' |
|||
<lang ruby>class SillyError < Exception |
<lang ruby>class SillyError < Exception |
||
Line 1,011: | Line 1,031: | ||
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). |
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 |
<lang ruby>def spam |
||
Line 1,017: | Line 1,037: | ||
end</lang> |
end</lang> |
||
'''Handling an exception''' |
|||
rescue/else/ensure |
rescue/else/ensure |
||
Line 1,035: | Line 1,055: | ||
The "rescue" clause is like the "catch" clause in other languages. The "ensure" clause is like the "finally" clause in other languages. |
The "rescue" clause is like the "catch" clause in other languages. The "ensure" clause is like the "finally" clause in other languages. |
||
'''Catch/Throw'''<br> |
|||
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. |
||
Line 1,050: | Line 1,070: | ||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
'''Handling Exceptions''' |
|||
<lang slate>se@(SceneElement traits) doWithRestart: block |
<lang slate>se@(SceneElement traits) doWithRestart: block |
||
Line 1,057: | Line 1,077: | ||
].</lang> |
].</lang> |
||
'''Define Exceptions''' |
|||
<lang slate>conditions define: #Abort &parents: {Restart}. |
<lang slate>conditions define: #Abort &parents: {Restart}. |
||
Line 1,078: | Line 1,098: | ||
].</lang> |
].</lang> |
||
'''Throwing Exceptions'''<br> |
|||
{{Lines_too_long}} |
{{Lines_too_long}} |
||
<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''' |
|||
<lang sml>exception MyException; |
<lang sml>exception MyException; |
||
exception MyDataException of int; (* can be any first-class type, not just int *)</lang> |
exception MyDataException of int; (* can be any first-class type, not just int *)</lang> |
||
'''Throw Exceptions''' |
|||
<lang sml>fun f() = raise MyException; |
<lang sml>fun f() = raise MyException; |
||
fun g() = raise MyDataException 22;</lang> |
fun g() = raise MyDataException 22;</lang> |
||
'''Catch Exceptions''' |
|||
<lang sml>val x = f() handle MyException => 22; |
<lang sml>val x = f() handle MyException => 22; |
||
val y = f() handle MyDataException x => x;</lang> |
val y = f() handle MyDataException x => x;</lang> |
||
Line 1,154: | Line 1,175: | ||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
'''Defining exceptions''' |
|||
<lang vbnet>Class MyException |
<lang vbnet>Class MyException |
||
Inherits Exception |
Inherits Exception |
||
Line 1,160: | Line 1,181: | ||
End Class</lang> |
End Class</lang> |
||
⚫ | |||
⚫ | |||
<lang vbnet>Sub foo() |
<lang vbnet>Sub foo() |
||
Throw New MyException |
Throw New MyException |
||
End Sub</lang> |
End Sub</lang> |
||
'''Catching exceptions''' |
|||
<lang vbnet>Sub bar() |
<lang vbnet>Sub bar() |
||
Try |
Try |
||
Line 1,186: | Line 1,208: | ||
The major limitations are that nested Try/Catch blocks must be constructed by the user, and that the User Defined Labels required for the Catch/Finally blocks may not be reused within a subroutine. For these reasons, it is conventional to only have only 1 Try/Catch block per subroutine. |
The major limitations are that nested Try/Catch blocks must be constructed by the user, and that the User Defined Labels required for the Catch/Finally blocks may not be reused within a subroutine. For these reasons, it is conventional to only have only 1 Try/Catch block per subroutine. |
||
'''Throw exceptions''' |
|||
<lang vba>Sub foo1() |
<lang vba>Sub foo1() |
||
err.raise(vbObjectError + 1050) |
err.raise(vbObjectError + 1050) |
||
Line 1,196: | Line 1,218: | ||
</lang> |
</lang> |
||
'''Catching exceptions''' |
|||
<lang vba>Sub bar1() |
<lang vba>Sub bar1() |
||
'by convention, a simple handler |
'by convention, a simple handler |