Content deleted Content added
No edit summary Tags: Mobile edit Mobile app edit iOS app edit App section source |
|||
(29 intermediate revisions by 18 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 46 ⟶ 47:
=== Assembly language ===
{{Further|Assembly language}}
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 ===
Line 187 ⟶ 202:
{{Further|C++}}
<syntaxhighlight lang="cpp">
import std;
int main() {
try {
// do something (might throw an exception)
}▼
// handle a runtime_error e
▲ catch (const std::exception& e) {
} catch (const
// catches all exceptions as e
}▼
} catch (...) {
// catches all
▲ }
}
</syntaxhighlight>
Line 254 ⟶ 269:
try {
// code which could result in an exception
} catch (any e){
retry;
Line 417 ⟶ 431:
<syntaxhighlight lang="cpp">
import std;
int main() {
try {▼
throw static_cast<int>(42);
▲ try
std::println("(0,{})", e);
std::println("(1,{})", e);
▲ }
}
</syntaxhighlight>
Line 454 ⟶ 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 not be run when System.exit() is called and in other system-wide exceptional conditions (e.g. power loss).
// 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>
Line 466 ⟶ 493:
// Statements in which exceptions might be thrown
throw new Error("error");
} catch (error) {
// Statements that execute in the event of an exception
} finally {
Line 484 ⟶ 511:
try {
throw 12345; // primitive number
} catch (error) {
console.log(error); // logs 12345 as a primitive number to the console
}
Line 493 ⟶ 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 507 ⟶ 534:
var example = null;
example.toString();
} catch (error) {
if (error.type === "TypeError") {
// Variable might be null
Line 522 ⟶ 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 559 ⟶ 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>
Line 784 ⟶ 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 797 ⟶ 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.
Line 962 ⟶ 999:
=== S-Lang ===
{{Further|S-Lang
try
Line 983 ⟶ 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 ===
Line 1,091 ⟶ 1,128:
End Property
End Class
</syntaxhighlight><ref name="VBexhandle">
=== Visual Basic 6 ===
Line 1,103 ⟶ 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,121 ⟶ 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,129 ⟶ 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 SOME_ERRORNUMBER
'exception handling
Line 1,202 ⟶ 1,239:
{{Further|Visual Prolog}}
<syntaxhighlight lang="
try
% Block to protect
Line 1,214 ⟶ 1,251:
=== X++ ===
{{Further|Microsoft Dynamics AX}}
<syntaxhighlight lang="
public static void Main(Args _args)
{
Line 1,245 ⟶ 1,282:
[[Category:Programming language syntax]]
[[Category:Control flow]]
[[Category:Articles with example code]]▼
[[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]]
|