Java 7 try-with-resources: Difference between revisions
Jump to navigation
Jump to search
(Created page with "=External= * https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html =Internal= * Subjects =Overview=") |
|||
(6 intermediate revisions by the same user not shown) | |||
Line 2: | Line 2: | ||
* https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html | * https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html | ||
* http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html | |||
=Internal= | =Internal= | ||
Line 8: | Line 9: | ||
=Overview= | =Overview= | ||
The try-with-resources statement is a <code>try</code> statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement, regardless of whether the sequence completes successfully or an exception is thrown. The programmer does not need to explicitly close resources. | |||
Local variables declared as resources in a try-with-resources statement are [[Java_final_Keyword#Overview|implicitly final]]. | |||
<syntaxhighlight lang='java'> | |||
try (BufferedReader br = new BufferedReader(new FileReader(file))) { | |||
// ... | |||
} | |||
catch(IOException e) { | |||
// ... | |||
} | |||
</syntaxhighlight> | |||
=AutoCloseable= | |||
=TODO= | |||
* Can be used with streams: [[Java_8_Streams_API#From_Files]] |
Latest revision as of 18:36, 12 June 2021
External
- https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
- http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html
Internal
Overview
The try-with-resources statement is a try
statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement, regardless of whether the sequence completes successfully or an exception is thrown. The programmer does not need to explicitly close resources.
Local variables declared as resources in a try-with-resources statement are implicitly final.
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
// ...
}
catch(IOException e) {
// ...
}
AutoCloseable
TODO
- Can be used with streams: Java_8_Streams_API#From_Files