Exception handling · Topic 4 of 7
try-with-resources
Definition​
try-with-resources closes things like files and connections for you, even when an exception happens. The resource must implement AutoCloseable. If both the body and close fail, the close error is attached to the first one as a suppressed exception.
Example code​
A resource that is closed automatically, in reverse order
class Resource implements AutoCloseable {
private final String name;
Resource(String name) {
this.name = name;
System.out.println("open " + name);
}
void use() { System.out.println("use " + name); }
@Override
public void close() { System.out.println("close " + name); }
}
class Demo {
public static void main(String[] args) {
try (Resource db = new Resource("database"); Resource file = new Resource("file")) {
db.use();
file.use();
throw new IllegalStateException("something failed");
} catch (IllegalStateException e) {
System.out.println("caught: " + e.getMessage()); // resources were already closed
}
}
}
// Output:
// open database
// open file
// use database
// use file
// close file
// close database
// caught: something failed
Finished this page? Track your progress (saved only in your browser).