Content deleted Content added
No edit summary Tags: Mobile edit Mobile web edit |
No edit summary Tags: Mobile edit Mobile app edit iOS app edit App section source |
||
(6 intermediate revisions by 4 users not shown) | |||
Line 207:
try {
// do something (might throw an exception)
} catch (const std::runtime_error e) {
// handle a runtime_error e
} catch (const std::exception& e) {
//
} catch (...) {
// catches all
}
}
Line 268 ⟶ 269:
try {
// code which could result in an exception
} catch (any e){
retry;
Line 473:
}
</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);
Line 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 511:
try {
throw 12345; // primitive number
} catch (error) {
console.log(error); // logs 12345 as a primitive number to the console
}
Line 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 534:
var example = null;
example.toString();
} catch (error) {
if (error.type === "TypeError") {
// Variable might be null
Line 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 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>
|