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;








2















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?










share|improve this question






























    2















    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?










    share|improve this question


























      2












      2








      2


      1






      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?










      share|improve this question
















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 22 at 4:03







      edyucheng

















      asked Mar 22 at 3:56









      edyuchengedyucheng

      257




      257






















          2 Answers
          2






          active

          oldest

          votes


















          1














          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.






          share|improve this answer























          • 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


















          0














          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






          share|improve this answer























            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
            );



            );













            draft saved

            draft discarded


















            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









            1














            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.






            share|improve this answer























            • 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















            1














            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.






            share|improve this answer























            • 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













            1












            1








            1







            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.






            share|improve this answer













            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.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            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

















            • 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













            0














            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






            share|improve this answer



























              0














              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






              share|improve this answer

























                0












                0








                0







                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






                share|improve this answer













                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







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 22 at 4:03









                mjuarezmjuarez

                10.5k73954




                10.5k73954



























                    draft saved

                    draft discarded
















































                    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.




                    draft saved


                    draft discarded














                    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





















































                    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







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현