Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Java syntax
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
====<code>try</code>-with-resources statements==== <code>try</code>-with-resources statements are a special type of <code>try-catch-finally</code> statements introduced as an implementation of the [[dispose pattern]] in Java SE 7. In a <code>try</code>-with-resources statement the <code>try</code> keyword is followed by initialization of one or more resources that are released automatically when the <code>try</code> block execution is finished. Resources must implement <code>java.lang.AutoCloseable</code>. <code>try</code>-with-resources statements are not required to have a <code>catch</code> or <code>finally</code> block unlike normal <code>try-catch-finally</code> statements. <syntaxhighlight lang="java"> try (FileOutputStream fos = new FileOutputStream("filename"); XMLEncoder xEnc = new XMLEncoder(fos)) { xEnc.writeObject(object); } catch (IOException ex) { Logger.getLogger(Serializer.class.getName()).log(Level.SEVERE, null, ex); } </syntaxhighlight> Since Java 9 it is possible to use already declared variables: <syntaxhighlight lang="java"> FileOutputStream fos = new FileOutputStream("filename"); XMLEncoder xEnc = new XMLEncoder(fos); try (fos; xEnc) { xEnc.writeObject(object); } catch (IOException ex) { Logger.getLogger(Serializer.class.getName()).log(Level.SEVERE, null, ex); } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)