Exception handling syntax: Difference between revisions

Content deleted Content added
spelling (WP:Typo Team)
No edit summary
Tags: Mobile edit Mobile app edit iOS app edit App section source
 
(13 intermediate revisions by 8 users not shown)
Line 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 269:
try {
// code which could result in an exception
 
} catch (any e){
retry;
Line 432 ⟶ 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 469 ⟶ 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 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 481 ⟶ 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 499 ⟶ 511:
try {
throw 12345; // primitive number
} catch (error) {
console.log(error); // logs 12345 as a primitive number to the console
}
Line 508 ⟶ 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 522 ⟶ 534:
var example = null;
example.toString();
} catch (error) {
if (error.type === "TypeError") {
// Variable might be null
Line 537 ⟶ 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 574 ⟶ 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 799 ⟶ 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">