Exception handling syntax: Difference between revisions

Content deleted Content added
m clean up
No edit summary
Tags: Mobile edit Mobile app edit iOS app edit App section source
 
(32 intermediate revisions by 21 users not shown)
Line 1:
{{Short description|Keywords provided by a programming language}}
'''Exception handling syntax''' is the set of keywords and/or structures provided by a computer [[programming language]] to allow [[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.
{{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 45 ⟶ 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 186 ⟶ 202:
{{Further|C++}}
<syntaxhighlight lang="cpp">
import std;
#include <exception>
 
int main() {
try {
// do something (might throw an exception)
} catch (const std::exception&runtime_error e) {
}
// handle a runtime_error e
catch (const std::exception& e) {
} catch (const // handle std::exception& e) {
// catches all exceptions as e
}
} catch (...) {
// catches all exceptionsthrown types (including primitives or objects that do nit extend exception), not already caught by a catch block before
}
// can be used to catch exception of unknown or irrelevant type
}
}
</syntaxhighlight>
Line 253 ⟶ 269:
try {
// code which could result in an exception
 
} catch (any e){
retry;
Line 416 ⟶ 431:
 
<syntaxhighlight lang="cpp">
import std;
#include <iostream>
 
using namespace std;
int main() {
try {
{
throw static_cast<int>(42);
try
{throw} catch(intdouble e)42;} {
std::println("(0,{})", e);
catch(double e)
{cout} << "catch(0," <<int e << ")" << endl;}{
std::println("(1,{})", e);
catch(int e)
}
{cout << "(1," << e << ")" << endl;}
}
</syntaxhighlight>
Line 453 ⟶ 468:
} finally {
// Always run when leaving the try block (including finally clauses), regardless of whether any exceptions were thrown or whether they were handled.
// Often used to cleanCleans up and closecloses resources suchacquired in athe filetry handlesblock.
// May nonot 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 465 ⟶ 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 483 ⟶ 511:
try {
throw 12345; // primitive number
} catch (error) {
console.log(error); // logs 12345 as a primitive number to the console
}
Line 492 ⟶ 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 506 ⟶ 534:
var example = null;
example.toString();
} catch (error) {
if (error.type === "TypeError") {
// Variable might be null
Line 521 ⟶ 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 558 ⟶ 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 688 ⟶ 726:
<syntaxhighlight lang="objc">
NSException *exception = [NSException exceptionWithName:@"myException"
reason:@"whateveryourReason" userInfo:nil];
</syntaxhighlight>
 
Line 783 ⟶ 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]{{dead link|date=October 2020}} or [https://stackoverflow.com/a/10343025]; ''cf''. [http://mvp.kablamo.org/essentials/die-eval/]). But at the cost of not being able to use return values:
 
<syntaxhighlight lang="perl">
Line 796 ⟶ 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}} and, {{Perl2|Try::Tiny}} bothand {{Perl2|Nice::Try}} all allow the use of try/catch/finally syntax instead of boilerplate to handle exceptions correctly.
* {{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 961 ⟶ 999:
 
=== S-Lang ===
{{Further|S-Lang (programming library)}}
 
try
Line 982 ⟶ 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 [[S-Lang (programming language)|S-Lang]] objects.
 
=== Smalltalk ===
Line 1,090 ⟶ 1,128:
End Property
End Class
</syntaxhighlight><ref name="VBexhandle">[{{Cite web |url=https://sites.google.com/site/truetryforvisualbasic/ |title=Try-Catch for VB] |access-date=2012-03-17 |archive-date=2016-04-16 |archive-url=https://web.archive.org/web/20160416093023/https://sites.google.com/site/truetryforvisualbasic/ |url-status=dead }}</ref>
 
=== Visual Basic 6 ===
Line 1,102 ⟶ 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 buildbuilt-in object Err. If there is no error handler, calling procedure can catch exception by same syntax
'...
 
Line 1,120 ⟶ 1,158:
 
MsgBox Err.Number & " " & Err.Source & " " & Erl & " " & Err.Description & " " & Err.LastDllError 'show message box with important error properties
'Erl is VB6 buildbuilt-in line number global variable (if used). Typically is used some kind of IDE Add-In, which labels every code line with number before compilation
Resume FinallyLabel
</syntaxhighlight>
Line 1,128 ⟶ 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 buildbuilt-in Err object)
Case SOME_ERRORNUMBER
'exception handling
Line 1,201 ⟶ 1,239:
{{Further|Visual Prolog}}
 
<syntaxhighlight lang="prologvisualprolog">
try
% Block to protect
Line 1,213 ⟶ 1,251:
=== X++ ===
{{Further|Microsoft Dynamics AX}}
<syntaxhighlight lang="javax++">
public static void Main(Args _args)
{
Line 1,244 ⟶ 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]]