Content deleted Content added
→Java: more info on try-with-resources |
|||
Line 474:
}
</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>https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html</ref>
<syntaxhighlight lang="java">
try (FileReader fr = new FileReader(path);
Line 482 ⟶ 481:
} catch (IOException ioe) {
// Deal with exception.
} // File and stream in the try statement are automatically closed afterwards.▼
finally {
// A finally block can be included here as well, and will run after the resources in the try statements are closed.
}
▲// File and stream in the try statement are automatically closed afterwards.
</syntaxhighlight>
|