Content deleted Content added
→Python: file() is deprecated, the documentation recommends open() |
No edit summary Tags: Mobile edit Mobile app edit iOS app edit App section source |
||
(45 intermediate revisions by 26 users not shown) | |||
Line 1:
{{Short description|Keywords provided by a programming language}}
{{Cleanup bare URLs|date=August 2022}}
'''Exception handling syntax''' is the set of keywords and/or structures provided by a computer [[programming language]] to allow [[exception handling (programming)|exception handling]], which separates the handling of errors that arise during a program's operation from its ordinary processes. Syntax for exception handling varies between [[programming language]]s, partly to cover semantic differences but largely to fit into each language's overall [[syntax#Syntax in computer science|syntactic structure]]. Some languages do not call the relevant concept "[[exception handling]]"; others may not have direct facilities for it, but can still provide means to implement it.
Most commonly, error handling uses a <code>try...[catch...][finally...]</code> block, and errors are created via a <code>throw</code> statement, but there is significant variation in naming and syntax.
Line 6 ⟶ 8:
=== Ada ===
{{Further
{{Wikibooks|Ada Programming|Exceptions}}
Line 44 ⟶ 46:
=== Assembly language ===
{{Further
Most assembly languages will have a macro instruction or an interrupt address available for the particular system to intercept events such as illegal op codes, program check, data errors, overflow, [[divide by zero]], and other such. IBM and Univac mainframes had the [[STXIT]] macro. [[Digital Equipment Corporation]] [[RT11]] systems had trap vectors for program errors, i/o interrupts, and such. [[DOS]] has certain interrupt addresses. [[Microsoft Windows]] has specific module calls to trap program errors.
=== ATS ===
{{Further|ATS (programming language)}}
<syntaxhighlight lang="ocaml">
exception MyException of (string, int) (* exceptions can carry a value *)
implement main0 (): void =
try $raise MyException("not enough food", 2) with
| ~MyException(s, i) => begin
$extfcall(void, "fprintf", stderr_ref, "%s: %d", s, i);
fileref_close(stderr_ref);
end
</syntaxhighlight>
=== Bash ===
{{Further
<syntaxhighlight lang="bash">
Line 69 ⟶ 85:
=== BASIC ===
{{Further
An ''On Error goto/gosub'' structure is used in BASIC and is quite different from modern exception handling; in BASIC there is only one global handler whereas in modern exception handling, exception handlers are stacked.
Line 85 ⟶ 101:
=== C ===
{{Further
In any case, a possible way to implement exception handling in standard C is to use [[setjmp.h|setjmp/longjmp]] functions:
<syntaxhighlight lang="c">
#include <setjmp.h>
Line 118 ⟶ 136:
==== Microsoft-specific ====
{{Further
Two types exist:
* Structured Exception Handling (SEH)
Line 150 ⟶ 168:
=== C# ===
{{Further
A <code>try</code> block must have at least one <code>catch</code> or <code>finally</code> clause and at most one <code>finally</code> clause.
<syntaxhighlight lang="csharp">
Line 182 ⟶ 200:
=== C++ ===
{{Further
<syntaxhighlight lang="cpp">
import std;
int main() {
try {
// do something (might throw an exception)
} catch (const std::runtime_error e) {
// handle a runtime_error e
} catch (const
// catches all exceptions as e
} catch (...) {
// catches all
}
}
</syntaxhighlight>
Line 201 ⟶ 219:
=== ColdFusion Markup Language (CFML) ===
{{Further
==== Script syntax ====
Line 242 ⟶ 260:
==== Railo-Lucee specific syntax ====
{{Further
Added to the standard syntax above, CFML dialects of [[Railo]] and [[Lucee]] allow a <code>retry</code> statement.<ref>https://issues.jboss.org/browse/RAILO-2176 # JBoss Community issue tracker ticket for adding <code>retry</code></ref>
This statement returns processing to the start of the prior <code>try</code> block.
Line 250 ⟶ 268:
<syntaxhighlight lang="javascript">
try {
// code which could result in an exception
} catch (any e){
retry;
Line 270 ⟶ 287:
=== D ===
{{Further
<syntaxhighlight lang="d">
import std.stdio; // for writefln()
Line 291 ⟶ 308:
=== Delphi ===
{{Further
; Exception declarations
<syntaxhighlight lang="delphi">
Line 307 ⟶ 324:
raise Exception.Create('Message');
raise Exception.CreateFmt('Message with values: %d, %d',[value1, value2]); // See SysUtils.Format() for parameters.
raise ECustom.CreateCustom(X);
Line 340 ⟶ 357:
=== Erlang ===
{{Further
<syntaxhighlight lang="erlang">
try
Line 354 ⟶ 371:
=== F# ===
{{Further
In addition to the OCaml-based <code>try...with</code>, F# also has the separate <code>try...finally</code> construct, which has the same behavior as a try block with a <code>finally</code> clause in other .NET languages.
Line 391 ⟶ 408:
=== Haskell ===
{{Further
Haskell does not have special syntax for exceptions. Instead, a {{Haskell|try}}/{{Haskell|catch}}/{{Haskell|finally}}/{{Haskell|etc}}. interface is provided by functions.
Line 413 ⟶ 430:
in analogy with this C++
<syntaxhighlight lang="
import std;
int main() {
try {
throw static_cast<int>(42);
std::println("(0,{})", e);
std::println("(1,{})", e);
}
}
</syntaxhighlight>
Line 440 ⟶ 457:
=== Java ===
{{Further
{{Wikibooks|Java Programming|Exceptions}}
A <code>try</code> block must have at least one <code>catch</code> or <code>finally</code> clause and at most one <code>finally</code> clause.
Line 451 ⟶ 468:
} finally {
// Always run when leaving the try block (including finally clauses), regardless of whether any exceptions were thrown or whether they were handled.
//
// May
// Rarely used after try-with-resources was added to the language (see below).
}
</syntaxhighlight>
If multiple resources are acquired, the correct way to deal with them is with nested try blocks.<ref>Bloch, Joshua (2018). ''Effective Java, Third Edition''. Addison-Wesley. Item 9, p. 54. {{ISBN|978-0-13-468599-1}}</ref> For this reason and others, ''try-with-resources'' was added to the language to almost entirely replace finally clauses. Resources acquired in a parentheses after the try keyword will be cleaned up automatically. Classes used in these statements must implement an interface called AutoCloseable.<ref>{{cite web | url=https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html | title=The try-with-resources Statement (The Java™ Tutorials > Essential Java Classes > Exceptions) }}</ref>
<syntaxhighlight lang="java">
try (FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr)) {
// Normal execution path.
} catch (IOException ioe) {
// Deal with exception.
} // Resources in the try statement are automatically closed afterwards.
finally {
// A finally clause can be included, and will run after the resources in the try statements are closed.
}
</syntaxhighlight>
=== JavaScript ===
{{Further
The design of JavaScript makes loud/hard errors very uncommon. [[
<syntaxhighlight lang="javascript">
try {
// Statements in which exceptions might be thrown
throw new Error("error");
} catch (error) {
// Statements that execute in the event of an exception
} finally {
Line 481 ⟶ 511:
try {
throw 12345; // primitive number
} catch (error) {
console.log(error); // logs 12345 as a primitive number to the console
}
Line 490 ⟶ 520:
// Example in Java
try {
Integer i = null;
i.intValue(); // throws a NullPointerException
} catch (NullPointerException error) {
// Variable might be null
} catch (ArithmeticException error) {
// Handle problems with numbers
}
</syntaxhighlight>
Line 504 ⟶ 534:
var example = null;
example.toString();
} catch (error) {
if (error.type === "TypeError") {
// Variable might be null
Line 519 ⟶ 549:
var example = null;
example.toString();
} catch (error) {
if (error.type !== "TypeError") throw error;
// Variable might be null
}
} catch (error) {
if (error.type !== "RangeError") throw error;
// Handle problems with numbers
Line 556 ⟶ 586:
obj.selfPropExample = obj; // circular reference
throw obj;
} catch (error) {
// Statements that execute in the event of an exception
}
</syntaxhighlight>
=== Kotlin ===
{{Further|Kotlin (programming language)}}
<syntaxhighlight lang="kotlin">
try {
// Code that may throw an exception
} catch (e: SomeException) {
// Code for handling the exception
}
</syntaxhighlight>
=== Lisp ===
{{Further
==== Common Lisp ====
{{Further
<syntaxhighlight lang="lisp">
(ignore-errors (/ 1 0))
Line 583 ⟶ 623:
=== Lua ===
{{Further
Lua uses the <code>pcall</code> and <code>xpcall</code> functions, with <code>xpcall</code> taking a function to act as a <code>catch</code> block.
; Predefined function
Line 634 ⟶ 674:
=== Next Generation Shell ===
{{Further
; Defining custom exception type
Line 682 ⟶ 722:
=== Objective-C ===
{{Further
; Exception declarations
<syntaxhighlight lang="objc">
NSException *exception = [NSException exceptionWithName:@"myException"
reason:@"
</syntaxhighlight>
Line 721 ⟶ 761:
=== OCaml ===
{{Further
<syntaxhighlight lang="ocaml">
exception MyException of string * int (* exceptions can carry a value *)
Line 741 ⟶ 781:
=== Perl 5===
{{Further
The [[Perl]] mechanism for exception handling uses {{Perl2|die}} to throw an exception when wrapped inside an {{Perl2|eval { ... };}} block. After the {{Perl2|eval}}, the special variable {{Perl2|$@}} contains the value passed from {{Perl2|die}}.
Perl 5.005 added the ability to throw objects as well as strings. This allows better introspection and handling of types of exceptions.
Line 802 ⟶ 821:
The forms shown above can sometimes fail if the global variable {{Perl2|$@}} is changed between when the exception is thrown and when it is checked in the {{Perl2|if ($@)}} statement. This can happen in multi-threaded environments, or even in single-threaded environments when other code (typically
called in the destruction of some object) resets the global variable before the checking code.
The following example shows a way to avoid this problem (see [https://archive.today/20130415214802/http://www.perlfoundation.org/perl5/index.cgi?exception_handling]
<syntaxhighlight lang="perl">
Line 815 ⟶ 834:
Several modules in the Comprehensive Perl Archive Network ([[CPAN]]) expand on the basic mechanism:
* {{Perl2|Error}} provides a set of exception classes and allows use of the try/throw/catch/finally syntax.
* {{Perl2|TryCatch}}
* {{Perl2|Exception::Class}} is a base class and class-maker for derived exception classes. It provides a full structured [[stack trace]] in {{Perl2|$@->trace}} and {{Perl2|$@->trace->as_string}}.
* {{Perl2|Fatal}} overloads previously defined functions that return true/false e.g., {{Perl2|open}}, {{Perl2|close}}, {{Perl2|read}}, {{Perl2|write}}, etc. This allows built-in functions and others to be used as if they threw exceptions.
=== PHP ===
{{Further
<syntaxhighlight lang="php">
// Exception handling is only available in PHP versions 5 and greater.
Line 836 ⟶ 855:
=== PowerBuilder ===
{{Further
Exception handling is available in PowerBuilder versions 8.0 and above.
Line 850 ⟶ 869:
=== PowerShell ===
{{Further
==== Version 1.0 ====
Line 878 ⟶ 897:
=== Python ===
{{Further
<syntaxhighlight lang="python">
f = None
Line 896 ⟶ 915:
=== R ===
{{Further
<syntaxhighlight lang="splus">
tryCatch({
Line 914 ⟶ 933:
=== Rebol ===
{{Further
<syntaxhighlight lang="rebol">
REBOL [
Line 944 ⟶ 963:
=== Rexx ===
{{Further
<syntaxhighlight lang="rexx">
signal on halt;
Line 958 ⟶ 977:
=== Ruby ===
{{Further
<syntaxhighlight lang="ruby">
begin
Line 980 ⟶ 999:
=== S-Lang ===
{{Further
try
Line 1,001 ⟶ 1,020:
New exceptions may be created using the {{S-Lang|new_exception}} function, e.g.,
new_exception ("MyIOError", IOError, "My I/O Error");
will create an exception called {{S-Lang|MyIOError}} as a subclass of {{S-Lang|IOError}}. Exceptions may be generated using the throw statement, which can throw arbitrary [[
=== Smalltalk ===
{{Further
<syntaxhighlight lang="smalltalk">
[ "code that might throw an exception" ]
Line 1,014 ⟶ 1,033:
=== Swift ===
{{Further
Exception handling is supported since Swift 2.
<syntaxhighlight lang="swift">
Line 1,034 ⟶ 1,053:
=== Tcl ===
{{Further
<syntaxhighlight lang="tcl">
if { [ catch {
Line 1,060 ⟶ 1,079:
=== VBScript ===
{{Further
<syntaxhighlight lang="vbnet">
With New Try: On Error Resume Next
Line 1,067 ⟶ 1,086:
Case 0 'this line is required when using 'Case Else' clause because of the lack of "Is" keyword in VBScript Case statement
'no exception
Case
'exception handling
Case Else
Line 1,109 ⟶ 1,128:
End Property
End Class
</syntaxhighlight><ref name="VBexhandle">
=== Visual Basic 6 ===
{{Further
Exception handling syntax is very similar to Basic. Error handling is local on each procedure.
<syntaxhighlight lang="vbnet">
Line 1,121 ⟶ 1,140:
On Error Resume Next 'Object Err is set, but execution continues on next command. You can still use Err object to check error state.
'...
Err.Raise 6 ' Generate an "Overflow" error using
'...
Line 1,139 ⟶ 1,158:
MsgBox Err.Number & " " & Err.Source & " " & Erl & " " & Err.Description & " " & Err.LastDllError 'show message box with important error properties
'Erl is VB6
Resume FinallyLabel
</syntaxhighlight>
Line 1,147 ⟶ 1,166:
With New Try: On Error Resume Next 'Create new object of class "Try" and use it. Then set this object as default. Can be "Dim T As New Try: ... ... T.Catch
'do Something (only one statement recommended)
.Catch: On Error GoTo 0: Select Case .Number 'Call Try.Catch() procedure. Then switch off error handling. Then use "switch-like" statement on result of Try.Number property (value of property Err.Number of
Case
'exception handling
Case Is <> 0 'When Err.Number is zero, no error has occurred
Line 1,197 ⟶ 1,216:
==== Visual Basic .NET ====
{{Further
A <code>Try</code> block must have at least one clause <code>Catch</code> or <code>Finally</code> clause and at most one <code>Finally</code> clause.
<syntaxhighlight lang="vbnet">
Line 1,218 ⟶ 1,237:
=== Visual Prolog ===
{{Further
<syntaxhighlight lang="
try
% Block to protect
Line 1,228 ⟶ 1,247:
% Code will be executed regardles however the other parts behave
end try
</syntaxhighlight><ref>http://wiki.visual-prolog.com/index.php?title=Language_Reference/Terms#Try-catch-finally</ref>
=== X++ ===
{{Further
<syntaxhighlight lang="
public static void Main(Args _args)
{
Line 1,263 ⟶ 1,282:
[[Category:Programming language syntax]]
[[Category:Control flow]]
[[Category:Programming language comparisons]]
<!-- Hidden categories below -->
[[Category:Articles with example Ada code]]
[[Category:Articles with example BASIC code]]
[[Category:Articles with example C code]]
[[Category:Articles with example C++ code]]
[[Category:Articles with example C Sharp code]]
[[Category:Articles with example Haskell code]]
[[Category:Articles with example Java code]]
[[Category:Articles with example JavaScript code]]
[[Category:Articles with example Lisp (programming language) code]]
[[Category:Articles with example Objective-C code]]
[[Category:Articles with example OCaml code]]
[[Category:Articles with example Pascal code]]
[[Category:Articles with example Perl code]]
[[Category:Articles with example PHP code]]
[[Category:Articles with example Python (programming language) code]]
[[Category:Articles with example R code]]
[[Category:Articles with example Ruby code]]
[[Category:Articles with example Smalltalk code]]
[[Category:Articles with example Swift code]]
[[Category:Articles with example Tcl code]]
|