Should I declare EVERY resource in try-with-resources Statement? The 2019 Stack Overflow Developer Survey Results Are InAvoiding != null statementsWhat is a serialVersionUID and why should I use it?How do I declare and initialize an array in Java?Why should I not wrap every block in “try”-“catch”?Try-catch speeding up my code?Correct idiom for managing multiple chained resources in try-with-resources block?Transaction rollback on SQLException using new try-with-resources blockTry / Try-with-resources and Connection, Statement and ResultSet closingIs it a good practice to put ResultSet into a nested try-with-resources statement after Java7?What is the real sequence of work of the catch block and the resource closing?
How to save as into a customized destination on macOS?
Protecting Dualbooting Windows from dangerous code (like rm -rf)
Does the shape of a die affect the probability of a number being rolled?
Looking for Correct Greek Translation for Heraclitus
Can we generate random numbers using irrational numbers like π and e?
Loose spokes after only a few rides
Why did Acorn's A3000 have red function keys?
How come people say “Would of”?
Origin of "cooter" meaning "vagina"
Which Sci-Fi work first showed weapon of galactic-scale mass destruction?
Pokemon Turn Based battle (Python)
Why do UK politicians seemingly ignore opinion polls on Brexit?
How to type this arrow in math mode?
Is "plugging out" electronic devices an American expression?
Distributing a matrix
What is the meaning of Triage in Cybersec world?
Time travel alters history but people keep saying nothing's changed
How to deal with fear of taking dependencies
What are the motivations for publishing new editions of an existing textbook, beyond new discoveries in a field?
Can a flute soloist sit?
Why is the Constellation's nose gear so long?
How to check whether the reindex working or not in Magento?
A poker game description that does not feel gimmicky
Why isn't the circumferential light around the M87 black hole's event horizon symmetric?
Should I declare EVERY resource in try-with-resources Statement?
The 2019 Stack Overflow Developer Survey Results Are InAvoiding != null statementsWhat is a serialVersionUID and why should I use it?How do I declare and initialize an array in Java?Why should I not wrap every block in “try”-“catch”?Try-catch speeding up my code?Correct idiom for managing multiple chained resources in try-with-resources block?Transaction rollback on SQLException using new try-with-resources blockTry / Try-with-resources and Connection, Statement and ResultSet closingIs it a good practice to put ResultSet into a nested try-with-resources statement after Java7?What is the real sequence of work of the catch block and the resource closing?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
In many try-with-resource examples I have searched, Statement and ResultSet are declared separately. As the Java document mentioned, the close methods of resources are called in the opposite order of their creation.
try (Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql) )
catch (Exception e)
But now I have multiple queries in my function.
Can I make Statement and ResultSet in just one line ? My code is like:
try (ResultSet rs = con.createStatement().executeQuery(sql);
ResultSet rs2 = con.createStatement().executeQuery(sql2);
ResultSet rs3 = con.createStatement().executeQuery(sql3))
catch (Exception e)
If I only declare them in one line, does it still close resource of both ResultSet and Statement?
java try-catch try-with-resources
add a comment |
In many try-with-resource examples I have searched, Statement and ResultSet are declared separately. As the Java document mentioned, the close methods of resources are called in the opposite order of their creation.
try (Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql) )
catch (Exception e)
But now I have multiple queries in my function.
Can I make Statement and ResultSet in just one line ? My code is like:
try (ResultSet rs = con.createStatement().executeQuery(sql);
ResultSet rs2 = con.createStatement().executeQuery(sql2);
ResultSet rs3 = con.createStatement().executeQuery(sql3))
catch (Exception e)
If I only declare them in one line, does it still close resource of both ResultSet and Statement?
java try-catch try-with-resources
add a comment |
In many try-with-resource examples I have searched, Statement and ResultSet are declared separately. As the Java document mentioned, the close methods of resources are called in the opposite order of their creation.
try (Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql) )
catch (Exception e)
But now I have multiple queries in my function.
Can I make Statement and ResultSet in just one line ? My code is like:
try (ResultSet rs = con.createStatement().executeQuery(sql);
ResultSet rs2 = con.createStatement().executeQuery(sql2);
ResultSet rs3 = con.createStatement().executeQuery(sql3))
catch (Exception e)
If I only declare them in one line, does it still close resource of both ResultSet and Statement?
java try-catch try-with-resources
In many try-with-resource examples I have searched, Statement and ResultSet are declared separately. As the Java document mentioned, the close methods of resources are called in the opposite order of their creation.
try (Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql) )
catch (Exception e)
But now I have multiple queries in my function.
Can I make Statement and ResultSet in just one line ? My code is like:
try (ResultSet rs = con.createStatement().executeQuery(sql);
ResultSet rs2 = con.createStatement().executeQuery(sql2);
ResultSet rs3 = con.createStatement().executeQuery(sql3))
catch (Exception e)
If I only declare them in one line, does it still close resource of both ResultSet and Statement?
java try-catch try-with-resources
java try-catch try-with-resources
edited Mar 22 at 4:03
edyucheng
asked Mar 22 at 3:56
edyuchengedyucheng
257
257
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
When you have a careful look you will see that the concept is called try-with-resources.
Note the plural! The whole idea is that you can declare one or more resources in that single statement and the jvm guarantees proper handling.
In other words: when resources belong together semantically, it is good practice to declare them together.
con.createStatement().executeQuery(sql2);
creates a Statement object and a ResultSet object. Does it mean that Both statement and ResultSet objects' resources belong together semantically and both resources will be closed automatically?
– edyucheng
Mar 22 at 4:14
1
@edyucheng Yes, when they "belong" together, that seems reasonable. But please understand that such details really depend on your overall design/context. Beyond that, thanks for the quick accept ;-)
– GhostCat
Mar 22 at 9:50
add a comment |
Yes, and it works exactly as you put it in your question, multiple statements separated by semicolon.
You may declare one or more resources in a try-with-resources statement. The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:
try (
java.util.zip.ZipFile zf =
new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer =
java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
)
// Enumerate each entry
for (java.util.Enumeration entries =
zf.entries(); entries.hasMoreElements();)
// Get the entry name and write it to the output file
String newLine = System.getProperty("line.separator");
String zipEntryName =
((java.util.zip.ZipEntry)entries.nextElement()).getName() +
newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
ResultSet
implements AutoCloseable
, which means try-with-resources will also enforce closing it when it finishes using it.
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55292683%2fshould-i-declare-every-resource-in-try-with-resources-statement%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
When you have a careful look you will see that the concept is called try-with-resources.
Note the plural! The whole idea is that you can declare one or more resources in that single statement and the jvm guarantees proper handling.
In other words: when resources belong together semantically, it is good practice to declare them together.
con.createStatement().executeQuery(sql2);
creates a Statement object and a ResultSet object. Does it mean that Both statement and ResultSet objects' resources belong together semantically and both resources will be closed automatically?
– edyucheng
Mar 22 at 4:14
1
@edyucheng Yes, when they "belong" together, that seems reasonable. But please understand that such details really depend on your overall design/context. Beyond that, thanks for the quick accept ;-)
– GhostCat
Mar 22 at 9:50
add a comment |
When you have a careful look you will see that the concept is called try-with-resources.
Note the plural! The whole idea is that you can declare one or more resources in that single statement and the jvm guarantees proper handling.
In other words: when resources belong together semantically, it is good practice to declare them together.
con.createStatement().executeQuery(sql2);
creates a Statement object and a ResultSet object. Does it mean that Both statement and ResultSet objects' resources belong together semantically and both resources will be closed automatically?
– edyucheng
Mar 22 at 4:14
1
@edyucheng Yes, when they "belong" together, that seems reasonable. But please understand that such details really depend on your overall design/context. Beyond that, thanks for the quick accept ;-)
– GhostCat
Mar 22 at 9:50
add a comment |
When you have a careful look you will see that the concept is called try-with-resources.
Note the plural! The whole idea is that you can declare one or more resources in that single statement and the jvm guarantees proper handling.
In other words: when resources belong together semantically, it is good practice to declare them together.
When you have a careful look you will see that the concept is called try-with-resources.
Note the plural! The whole idea is that you can declare one or more resources in that single statement and the jvm guarantees proper handling.
In other words: when resources belong together semantically, it is good practice to declare them together.
answered Mar 22 at 4:01
GhostCatGhostCat
96.1k1794161
96.1k1794161
con.createStatement().executeQuery(sql2);
creates a Statement object and a ResultSet object. Does it mean that Both statement and ResultSet objects' resources belong together semantically and both resources will be closed automatically?
– edyucheng
Mar 22 at 4:14
1
@edyucheng Yes, when they "belong" together, that seems reasonable. But please understand that such details really depend on your overall design/context. Beyond that, thanks for the quick accept ;-)
– GhostCat
Mar 22 at 9:50
add a comment |
con.createStatement().executeQuery(sql2);
creates a Statement object and a ResultSet object. Does it mean that Both statement and ResultSet objects' resources belong together semantically and both resources will be closed automatically?
– edyucheng
Mar 22 at 4:14
1
@edyucheng Yes, when they "belong" together, that seems reasonable. But please understand that such details really depend on your overall design/context. Beyond that, thanks for the quick accept ;-)
– GhostCat
Mar 22 at 9:50
con.createStatement().executeQuery(sql2);
creates a Statement object and a ResultSet object. Does it mean that Both statement and ResultSet objects' resources belong together semantically and both resources will be closed automatically?– edyucheng
Mar 22 at 4:14
con.createStatement().executeQuery(sql2);
creates a Statement object and a ResultSet object. Does it mean that Both statement and ResultSet objects' resources belong together semantically and both resources will be closed automatically?– edyucheng
Mar 22 at 4:14
1
1
@edyucheng Yes, when they "belong" together, that seems reasonable. But please understand that such details really depend on your overall design/context. Beyond that, thanks for the quick accept ;-)
– GhostCat
Mar 22 at 9:50
@edyucheng Yes, when they "belong" together, that seems reasonable. But please understand that such details really depend on your overall design/context. Beyond that, thanks for the quick accept ;-)
– GhostCat
Mar 22 at 9:50
add a comment |
Yes, and it works exactly as you put it in your question, multiple statements separated by semicolon.
You may declare one or more resources in a try-with-resources statement. The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:
try (
java.util.zip.ZipFile zf =
new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer =
java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
)
// Enumerate each entry
for (java.util.Enumeration entries =
zf.entries(); entries.hasMoreElements();)
// Get the entry name and write it to the output file
String newLine = System.getProperty("line.separator");
String zipEntryName =
((java.util.zip.ZipEntry)entries.nextElement()).getName() +
newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
ResultSet
implements AutoCloseable
, which means try-with-resources will also enforce closing it when it finishes using it.
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
add a comment |
Yes, and it works exactly as you put it in your question, multiple statements separated by semicolon.
You may declare one or more resources in a try-with-resources statement. The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:
try (
java.util.zip.ZipFile zf =
new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer =
java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
)
// Enumerate each entry
for (java.util.Enumeration entries =
zf.entries(); entries.hasMoreElements();)
// Get the entry name and write it to the output file
String newLine = System.getProperty("line.separator");
String zipEntryName =
((java.util.zip.ZipEntry)entries.nextElement()).getName() +
newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
ResultSet
implements AutoCloseable
, which means try-with-resources will also enforce closing it when it finishes using it.
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
add a comment |
Yes, and it works exactly as you put it in your question, multiple statements separated by semicolon.
You may declare one or more resources in a try-with-resources statement. The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:
try (
java.util.zip.ZipFile zf =
new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer =
java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
)
// Enumerate each entry
for (java.util.Enumeration entries =
zf.entries(); entries.hasMoreElements();)
// Get the entry name and write it to the output file
String newLine = System.getProperty("line.separator");
String zipEntryName =
((java.util.zip.ZipEntry)entries.nextElement()).getName() +
newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
ResultSet
implements AutoCloseable
, which means try-with-resources will also enforce closing it when it finishes using it.
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
Yes, and it works exactly as you put it in your question, multiple statements separated by semicolon.
You may declare one or more resources in a try-with-resources statement. The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:
try (
java.util.zip.ZipFile zf =
new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer =
java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
)
// Enumerate each entry
for (java.util.Enumeration entries =
zf.entries(); entries.hasMoreElements();)
// Get the entry name and write it to the output file
String newLine = System.getProperty("line.separator");
String zipEntryName =
((java.util.zip.ZipEntry)entries.nextElement()).getName() +
newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
ResultSet
implements AutoCloseable
, which means try-with-resources will also enforce closing it when it finishes using it.
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
answered Mar 22 at 4:03
mjuarezmjuarez
10.5k73954
10.5k73954
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55292683%2fshould-i-declare-every-resource-in-try-with-resources-statement%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown