Exception handling syntax: Difference between revisions

Content deleted Content added
Sipraj (talk | contribs)
m Updating printstacktrace
Tag: Reverted
No edit summary
Tags: Mobile edit Mobile app edit iOS app edit App section source
 
(39 intermediate revisions by 24 users not shown)
Line 1:
{{Short description|Keywords provided by a programming language}}
<ref>[https://tedblob.com/java-printstacktrace/ title=Java printstacktrace]</ref>'''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 6 ⟶ 8:
 
=== Ada ===
{{Further information|Ada (programming language)}}
{{Wikibooks|Ada Programming|Exceptions}}
 
Line 44 ⟶ 46:
 
=== Assembly language ===
{{Further information|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 ===
{{Further information|Bash (Unix shell)}}
 
<syntaxhighlight lang="bash">
Line 69 ⟶ 85:
 
=== BASIC ===
{{Further information|BASIC}}
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 information|C (programming language)}}
C does not provide direct support to exception handling: it is the programmer's responsibility to prevent errors in the first place and test return values from the functions.
 
Line 120 ⟶ 136:
 
==== Microsoft-specific ====
{{Further information|Microsoft-specific exception handling mechanisms}}
Two types exist:
* Structured Exception Handling (SEH)
Line 152 ⟶ 168:
 
=== C# ===
{{Further information|C Sharp (programming language)}}
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 184 ⟶ 200:
 
=== C++ ===
{{Further information|C++}}
<syntaxhighlight lang="cpp">
import std;
#include <exception>
 
int main() {
try {
// do something (might throw an exception)
} catch (const std::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 203 ⟶ 219:
 
=== ColdFusion Markup Language (CFML) ===
{{Further information|ColdFusion Markup Language}}
 
==== Script syntax ====
Line 244 ⟶ 260:
 
==== Railo-Lucee specific syntax ====
{{Further information|Railo|Lucee}}
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 252 ⟶ 268:
<syntaxhighlight lang="javascript">
try {
// code which could result in an exception
 
} catch (any e){
retry;
Line 272 ⟶ 287:
 
=== D ===
{{Further information|D (programming language)}}
<syntaxhighlight lang="d">
import std.stdio; // for writefln()
Line 293 ⟶ 308:
 
=== Delphi ===
{{Further information|Delphi (programming language)}}
; Exception declarations
<syntaxhighlight lang="delphi">
Line 309 ⟶ 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 342 ⟶ 357:
 
=== Erlang ===
{{Further information|Erlang (programming language)}}
<syntaxhighlight lang="erlang">
try
Line 356 ⟶ 371:
 
=== F# ===
{{Further information|F_Sharp_(programming_language)}}
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 393 ⟶ 408:
 
=== Haskell ===
{{Further information|Haskell (programming language)}}
Haskell does not have special syntax for exceptions. Instead, a {{Haskell|try}}/{{Haskell|catch}}/{{Haskell|finally}}/{{Haskell|etc}}. interface is provided by functions.
 
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 442 ⟶ 457:
 
=== Java ===
{{Further information|Java (programming language)}}
{{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 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>
 
=== JavaScript ===
{{Further information|JavaScript}}
The design of JavaScript makes loud/hard errors very uncommon. [[Soft_errorSoft error|Soft/quiet errors]] are much more prevalent. Hard errors propagate to the nearest <code>try</code> statement, which must be followed by either a single <code>catch</code> clause, a single <code>finally</code> clause, or both.
<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 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>
 
=== Lisp ===
{{Further information|Lisp (programming language)}}
 
==== Common Lisp ====
{{Further information|Common Lisp}}
<syntaxhighlight lang="lisp">
(ignore-errors (/ 1 0))
Line 585 ⟶ 623:
 
=== Lua ===
{{Further information|Lua (programming language)}}
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 636 ⟶ 674:
 
=== Next Generation Shell ===
{{Further information|Next Generation Shell}}
 
; Defining custom exception type
Line 684 ⟶ 722:
 
=== Objective-C ===
{{Further information|Objective-C}}
; Exception declarations
<syntaxhighlight lang="objc">
NSException *exception = [NSException exceptionWithName:@"myException"
reason:@"whateveryourReason" userInfo:nil];
</syntaxhighlight>
 
Line 723 ⟶ 761:
 
=== OCaml ===
{{Further information|OCaml}}
<syntaxhighlight lang="ocaml">
exception MyException of string * int (* exceptions can carry a value *)
Line 743 ⟶ 781:
 
=== Perl 5===
{{Further information|Perl}}
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}}. However, scoping issues can make doing this correctly quite ugly:
 
<syntaxhighlight lang="perl">
my ($error, $failed);
{
local $@;
$failed = not eval {
# Code that could throw an exception (using 'die')
open(FILE, $file) || die "Could not open file: $!";
while (<FILE>) {
process_line($_);
}
close(FILE) || die "Could not close $file: $!";
return 1;
};
$error = $@;
}
 
if ($failed) {
warn "got error: $error";
}
</syntaxhighlight>
 
Perl 5.005 added the ability to throw objects as well as strings. This allows better introspection and handling of types of exceptions.
Line 804 ⟶ 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]{{deadlink|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 817 ⟶ 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.
 
=== PHP ===
{{Further information|PHP}}
<syntaxhighlight lang="php">
// Exception handling is only available in PHP versions 5 and greater.
Line 838 ⟶ 855:
 
=== PowerBuilder ===
{{Further information|PowerBuilder}}
Exception handling is available in PowerBuilder versions 8.0 and above.
 
Line 852 ⟶ 869:
 
=== PowerShell ===
{{Further information|PowerShell}}
 
==== Version 1.0 ====
Line 880 ⟶ 897:
 
=== Python ===
{{Further information|Python (programming language)}}
<syntaxhighlight lang="python">
f = None
Line 898 ⟶ 915:
 
=== R ===
{{Further information|R (programming language)}}
<syntaxhighlight lang="splus">
tryCatch({
Line 916 ⟶ 933:
 
=== Rebol ===
{{Further information|Rebol}}
<syntaxhighlight lang="rebol">
REBOL [
Line 946 ⟶ 963:
 
=== Rexx ===
{{Further information|Rexx}}
<syntaxhighlight lang="rexx">
signal on halt;
Line 960 ⟶ 977:
 
=== Ruby ===
{{Further information|Ruby (programming language)}}
<syntaxhighlight lang="ruby">
begin
Line 982 ⟶ 999:
 
=== S-Lang ===
{{Further information|S-Lang (programming library)}}
 
try
Line 1,003 ⟶ 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 ===
{{Further information|Smalltalk}}
<syntaxhighlight lang="smalltalk">
[ "code that might throw an exception" ]
Line 1,016 ⟶ 1,033:
 
=== Swift ===
{{Further information|Swift (programming language)}}
Exception handling is supported since Swift 2.
<syntaxhighlight lang="swift">
Line 1,036 ⟶ 1,053:
 
=== Tcl ===
{{Further information|Tcl}}
<syntaxhighlight lang="tcl">
if { [ catch {
Line 1,062 ⟶ 1,079:
 
=== VBScript ===
{{Further information|VBScript}}
<syntaxhighlight lang="vbnet">
With New Try: On Error Resume Next
Line 1,111 ⟶ 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 ===
{{Further information|Visual Basic}}
Exception handling syntax is very similar to Basic. Error handling is local on each procedure.
<syntaxhighlight lang="vbnet">
Line 1,123 ⟶ 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,141 ⟶ 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,149 ⟶ 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,199 ⟶ 1,216:
 
==== Visual Basic .NET ====
{{Further information|Visual Basic .NET}}
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,220 ⟶ 1,237:
 
=== Visual Prolog ===
{{Further information|Visual Prolog}}
 
http://wiki.visual-prolog.com/index.php?title=Language_Reference/Terms#Try-catch-finally
<syntaxhighlight lang="prologvisualprolog">
try
% Block to protect
Line 1,230 ⟶ 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>
</syntaxhighlight>
 
=== X++ ===
{{Further information|Microsoft Dynamics AX}}
<syntaxhighlight lang="javax++">
public static void Main(Args _args)
{
Line 1,265 ⟶ 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]]