Throwing multiple exceptions of the same type at once










0














My intent is to throw two Exceptions at once. The code:



 String str = "foo";

if (str.length() < 5)
throw new Exception("At least 5 characters."); // exception 1


if (!str.matches(".*[0-9]+.*"))
throw new Exception("At least 1 digit."); // exception 2



foo is less than 5 characters long and doesn't contain any digits. But when I run this program, only exception 1 is thrown.



How do I throw multiple exceptions (of the same type)? Or is my approach misled, and should I go about doing this differently?










share|improve this question





















  • maybe create your own exception hasProblemAandBException
    – Scary Wombat
    Nov 13 '18 at 2:11






  • 2




    This may be an xy problem -- whatever your overall goal, this approach does not appear to be right. Consider presenting us information on a higher level, on the strategy level rather than telling us your low level tactics-level approach.
    – Hovercraft Full Of Eels
    Nov 13 '18 at 2:11







  • 2




    you could just store a list of errors that have occured (adding an error for each constraint that is not met), then throw an exception containing the list of errors
    – mholle
    Nov 13 '18 at 2:14















0














My intent is to throw two Exceptions at once. The code:



 String str = "foo";

if (str.length() < 5)
throw new Exception("At least 5 characters."); // exception 1


if (!str.matches(".*[0-9]+.*"))
throw new Exception("At least 1 digit."); // exception 2



foo is less than 5 characters long and doesn't contain any digits. But when I run this program, only exception 1 is thrown.



How do I throw multiple exceptions (of the same type)? Or is my approach misled, and should I go about doing this differently?










share|improve this question





















  • maybe create your own exception hasProblemAandBException
    – Scary Wombat
    Nov 13 '18 at 2:11






  • 2




    This may be an xy problem -- whatever your overall goal, this approach does not appear to be right. Consider presenting us information on a higher level, on the strategy level rather than telling us your low level tactics-level approach.
    – Hovercraft Full Of Eels
    Nov 13 '18 at 2:11







  • 2




    you could just store a list of errors that have occured (adding an error for each constraint that is not met), then throw an exception containing the list of errors
    – mholle
    Nov 13 '18 at 2:14













0












0








0







My intent is to throw two Exceptions at once. The code:



 String str = "foo";

if (str.length() < 5)
throw new Exception("At least 5 characters."); // exception 1


if (!str.matches(".*[0-9]+.*"))
throw new Exception("At least 1 digit."); // exception 2



foo is less than 5 characters long and doesn't contain any digits. But when I run this program, only exception 1 is thrown.



How do I throw multiple exceptions (of the same type)? Or is my approach misled, and should I go about doing this differently?










share|improve this question













My intent is to throw two Exceptions at once. The code:



 String str = "foo";

if (str.length() < 5)
throw new Exception("At least 5 characters."); // exception 1


if (!str.matches(".*[0-9]+.*"))
throw new Exception("At least 1 digit."); // exception 2



foo is less than 5 characters long and doesn't contain any digits. But when I run this program, only exception 1 is thrown.



How do I throw multiple exceptions (of the same type)? Or is my approach misled, and should I go about doing this differently?







java exception exception-handling






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 13 '18 at 2:09









lefrostlefrost

377




377











  • maybe create your own exception hasProblemAandBException
    – Scary Wombat
    Nov 13 '18 at 2:11






  • 2




    This may be an xy problem -- whatever your overall goal, this approach does not appear to be right. Consider presenting us information on a higher level, on the strategy level rather than telling us your low level tactics-level approach.
    – Hovercraft Full Of Eels
    Nov 13 '18 at 2:11







  • 2




    you could just store a list of errors that have occured (adding an error for each constraint that is not met), then throw an exception containing the list of errors
    – mholle
    Nov 13 '18 at 2:14
















  • maybe create your own exception hasProblemAandBException
    – Scary Wombat
    Nov 13 '18 at 2:11






  • 2




    This may be an xy problem -- whatever your overall goal, this approach does not appear to be right. Consider presenting us information on a higher level, on the strategy level rather than telling us your low level tactics-level approach.
    – Hovercraft Full Of Eels
    Nov 13 '18 at 2:11







  • 2




    you could just store a list of errors that have occured (adding an error for each constraint that is not met), then throw an exception containing the list of errors
    – mholle
    Nov 13 '18 at 2:14















maybe create your own exception hasProblemAandBException
– Scary Wombat
Nov 13 '18 at 2:11




maybe create your own exception hasProblemAandBException
– Scary Wombat
Nov 13 '18 at 2:11




2




2




This may be an xy problem -- whatever your overall goal, this approach does not appear to be right. Consider presenting us information on a higher level, on the strategy level rather than telling us your low level tactics-level approach.
– Hovercraft Full Of Eels
Nov 13 '18 at 2:11





This may be an xy problem -- whatever your overall goal, this approach does not appear to be right. Consider presenting us information on a higher level, on the strategy level rather than telling us your low level tactics-level approach.
– Hovercraft Full Of Eels
Nov 13 '18 at 2:11





2




2




you could just store a list of errors that have occured (adding an error for each constraint that is not met), then throw an exception containing the list of errors
– mholle
Nov 13 '18 at 2:14




you could just store a list of errors that have occured (adding an error for each constraint that is not met), then throw an exception containing the list of errors
– mholle
Nov 13 '18 at 2:14












3 Answers
3






active

oldest

votes


















3














If you are checking against a list of possible problems, and you need to report all problems, then it may be neater to do it this way:



String str = "foo";

List<String> errors = new ArrayList<>();

if (str.length() < 5)
errors.add("At least 5 characters."); // exception 1


if (!str.matches(".*[0-9]+.*"))
errors.add("At least 1 digit."); // exception 2


// Check for more stuff

if (!errors.isEmpty())
throw new Exception("There are problem(s) found:n" + String.join("n", errors));



Effectively, this is the same as what was proposed by other answers/comments, but this approach is a little cleaner/neater for a more complex scenario.






share|improve this answer




























    1














    That is not possible. Instead test for the conditions you desire. Like,



    String str = "foo";
    boolean len = str.length() < 5;
    boolean digit = !str.matches(".*[0-9]+.*");
    if (len && digit)
    throw new Exception("At least 5 characters and 1 digit."); // both 1 and 2
    else if (len)
    throw new Exception("At least 5 characters."); // exception 1
    else if (digit)
    throw new Exception("At least 1 digit."); // exception 2






    share|improve this answer




























      0














      You can never throw more than one exception at a time, because they interrupt execution. You could test for each possible problem individually, and throw an exception at the end which contains each failed test separated in a way that is easy to parse (commas would probably be best here).






      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%2f53272760%2fthrowing-multiple-exceptions-of-the-same-type-at-once%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        3














        If you are checking against a list of possible problems, and you need to report all problems, then it may be neater to do it this way:



        String str = "foo";

        List<String> errors = new ArrayList<>();

        if (str.length() < 5)
        errors.add("At least 5 characters."); // exception 1


        if (!str.matches(".*[0-9]+.*"))
        errors.add("At least 1 digit."); // exception 2


        // Check for more stuff

        if (!errors.isEmpty())
        throw new Exception("There are problem(s) found:n" + String.join("n", errors));



        Effectively, this is the same as what was proposed by other answers/comments, but this approach is a little cleaner/neater for a more complex scenario.






        share|improve this answer

























          3














          If you are checking against a list of possible problems, and you need to report all problems, then it may be neater to do it this way:



          String str = "foo";

          List<String> errors = new ArrayList<>();

          if (str.length() < 5)
          errors.add("At least 5 characters."); // exception 1


          if (!str.matches(".*[0-9]+.*"))
          errors.add("At least 1 digit."); // exception 2


          // Check for more stuff

          if (!errors.isEmpty())
          throw new Exception("There are problem(s) found:n" + String.join("n", errors));



          Effectively, this is the same as what was proposed by other answers/comments, but this approach is a little cleaner/neater for a more complex scenario.






          share|improve this answer























            3












            3








            3






            If you are checking against a list of possible problems, and you need to report all problems, then it may be neater to do it this way:



            String str = "foo";

            List<String> errors = new ArrayList<>();

            if (str.length() < 5)
            errors.add("At least 5 characters."); // exception 1


            if (!str.matches(".*[0-9]+.*"))
            errors.add("At least 1 digit."); // exception 2


            // Check for more stuff

            if (!errors.isEmpty())
            throw new Exception("There are problem(s) found:n" + String.join("n", errors));



            Effectively, this is the same as what was proposed by other answers/comments, but this approach is a little cleaner/neater for a more complex scenario.






            share|improve this answer












            If you are checking against a list of possible problems, and you need to report all problems, then it may be neater to do it this way:



            String str = "foo";

            List<String> errors = new ArrayList<>();

            if (str.length() < 5)
            errors.add("At least 5 characters."); // exception 1


            if (!str.matches(".*[0-9]+.*"))
            errors.add("At least 1 digit."); // exception 2


            // Check for more stuff

            if (!errors.isEmpty())
            throw new Exception("There are problem(s) found:n" + String.join("n", errors));



            Effectively, this is the same as what was proposed by other answers/comments, but this approach is a little cleaner/neater for a more complex scenario.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 13 '18 at 2:27









            JaiJai

            5,73311231




            5,73311231























                1














                That is not possible. Instead test for the conditions you desire. Like,



                String str = "foo";
                boolean len = str.length() < 5;
                boolean digit = !str.matches(".*[0-9]+.*");
                if (len && digit)
                throw new Exception("At least 5 characters and 1 digit."); // both 1 and 2
                else if (len)
                throw new Exception("At least 5 characters."); // exception 1
                else if (digit)
                throw new Exception("At least 1 digit."); // exception 2






                share|improve this answer

























                  1














                  That is not possible. Instead test for the conditions you desire. Like,



                  String str = "foo";
                  boolean len = str.length() < 5;
                  boolean digit = !str.matches(".*[0-9]+.*");
                  if (len && digit)
                  throw new Exception("At least 5 characters and 1 digit."); // both 1 and 2
                  else if (len)
                  throw new Exception("At least 5 characters."); // exception 1
                  else if (digit)
                  throw new Exception("At least 1 digit."); // exception 2






                  share|improve this answer























                    1












                    1








                    1






                    That is not possible. Instead test for the conditions you desire. Like,



                    String str = "foo";
                    boolean len = str.length() < 5;
                    boolean digit = !str.matches(".*[0-9]+.*");
                    if (len && digit)
                    throw new Exception("At least 5 characters and 1 digit."); // both 1 and 2
                    else if (len)
                    throw new Exception("At least 5 characters."); // exception 1
                    else if (digit)
                    throw new Exception("At least 1 digit."); // exception 2






                    share|improve this answer












                    That is not possible. Instead test for the conditions you desire. Like,



                    String str = "foo";
                    boolean len = str.length() < 5;
                    boolean digit = !str.matches(".*[0-9]+.*");
                    if (len && digit)
                    throw new Exception("At least 5 characters and 1 digit."); // both 1 and 2
                    else if (len)
                    throw new Exception("At least 5 characters."); // exception 1
                    else if (digit)
                    throw new Exception("At least 1 digit."); // exception 2







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 13 '18 at 2:12









                    Elliott FrischElliott Frisch

                    153k1389178




                    153k1389178





















                        0














                        You can never throw more than one exception at a time, because they interrupt execution. You could test for each possible problem individually, and throw an exception at the end which contains each failed test separated in a way that is easy to parse (commas would probably be best here).






                        share|improve this answer

























                          0














                          You can never throw more than one exception at a time, because they interrupt execution. You could test for each possible problem individually, and throw an exception at the end which contains each failed test separated in a way that is easy to parse (commas would probably be best here).






                          share|improve this answer























                            0












                            0








                            0






                            You can never throw more than one exception at a time, because they interrupt execution. You could test for each possible problem individually, and throw an exception at the end which contains each failed test separated in a way that is easy to parse (commas would probably be best here).






                            share|improve this answer












                            You can never throw more than one exception at a time, because they interrupt execution. You could test for each possible problem individually, and throw an exception at the end which contains each failed test separated in a way that is easy to parse (commas would probably be best here).







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 13 '18 at 2:14









                            The Zach ManThe Zach Man

                            1146




                            1146



























                                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%2f53272760%2fthrowing-multiple-exceptions-of-the-same-type-at-once%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







                                這個網誌中的熱門文章

                                What does pagestruct do in Eviews?

                                Dutch intervention in Lombok and Karangasem

                                Channel Islands