Java Reference
In-Depth Information
finally {
statements
}
Example:
try {
FileWriter writer = new FileWriter( "foo.txt" );
writer.write(text);
writer.close();
}
catch (IOException e) {
Debug.reportError( "Writing text to file failed." );
Debug.reportError( "The exception is: " + e);
}
An exception statement may have any number of catch clauses . They are evaluated in order of
appearance, and only the first matching clause is executed. (A clause matches if the dynamic
type of the exception object being thrown is assignment-compatible with the declared exception
type in the catch clause.) The finally clause is optional.
Java 7 introduced two mainstream additions to the try statement: multi-catch and try-with-
resources, or automatic resource management (ARM).
Multiple exceptions may be handled in the same catch clause by writing the list of exception
types separated by the “ | ” symbol.
Example:
try {
...
var.doSomething();
...
}
catch (EOFException | FileNotFoundException e) {
...
}
Automatic resource management—also known as “try-with-resource”—recognizes that try
statements are often used to protect statements that use resources that should be closed when
their use is complete, both upon success and failure. The header of the try statement is amended
to include the opening of the resource—often a file—and the resource will be closed automati-
cally at the end of the try statement.
Example:
try (FileWriter writer = new FileWriter(filename)){
...
Use the writer ...
...
}
catch (IOException e) {
...
}
Search WWH ::




Custom Search