Exception handling in separate method for readabilityCatch multiple exceptions at once?How do you assert that a certain exception is thrown in JUnit 4 tests?The case against checked exceptionsHow to properly ignore exceptionsProper way to declare custom exceptions in modern Python?Manually raising (throwing) an exception in PythonHow to use java.net.URLConnection to fire and handle HTTP requestsExtracting common exception handling code of several methods in JavaUnderstanding checked vs unchecked exceptions in JavaCatch multiple exceptions in one line (except block)

How to compare two different formulations of a problem?

Sleeping solo in a double sleeping bag

Vacuum collapse -- why do strong metals implode but glass doesn't?

Was 'help' pronounced starting with a vowel sound?

Is a butterfly one or two animals?

Is "es" necessary in this sentence?

Potential new partner angry about first collaboration - how to answer email to close up this encounter in a graceful manner

What professions would a medieval village with a population of 100 need?

Was Switzerland really impossible to invade during WW2?

How to think about joining a company whose business I do not understand?

How to setup a teletype to a unix shell

Are there any plans for handling people floating away during an EVA?

Was Tuvok bluffing when he said that Voyager's transporters rendered the Kazon weapons useless?

Can we save the word "unique"?

Is it appropriate for a prospective landlord to ask me for my credit report?

Should my "average" PC be able to discern the potential of encountering a gelatinous cube from subtle clues?

Defense against attacks using dictionaries

Running script line by line automatically yet being asked before each line from second line onwards

Is it safe to remove the bottom chords of a series of garage roof trusses?

Is "stainless" a bulk or a surface property of stainless steel?

Thread-safe, Convenient and Performant Random Number Generator

Metal that glows when near pieces of itself

Do I have to learn /o/ or /ɔ/ separately?

Replace backtick ` with power ^ in math mode



Exception handling in separate method for readability


Catch multiple exceptions at once?How do you assert that a certain exception is thrown in JUnit 4 tests?The case against checked exceptionsHow to properly ignore exceptionsProper way to declare custom exceptions in modern Python?Manually raising (throwing) an exception in PythonHow to use java.net.URLConnection to fire and handle HTTP requestsExtracting common exception handling code of several methods in JavaUnderstanding checked vs unchecked exceptions in JavaCatch multiple exceptions in one line (except block)






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















Is it an anti-pattern to handle exception in a separate method?



Say i have a method that does some low-level IO and may throw an IOException, and i have a method foo() that calls the low-level IO method several times. Does it make sense to do the exception-handling in a 3rd method like this:



 public void foo() throws MyCheckedException 
// some stuff
goDoSomeIO(path1)
// some other stuff
goDoSomeIO(path2)
// some more stuff
goDoSomeIO(path3)



private String goDoSomeIO(String filePath) throws MyCheckedException
try
doSomeIO(filePath);
catch (IOException ioe)
LOG.error("Io failed at: " + filePath);
throw new MyCheckedException("Process failed because io failed", ioe)



private String doSomeIO(String filepath) throws IOException
//io stuff



I find this is more readable than it would be if the doSomeIO method did its own exception handling, or if the exception handling happend in foo.










share|improve this question
























  • it's a matter of style and it depends on the situation

    – firephil
    Mar 27 at 15:37

















2















Is it an anti-pattern to handle exception in a separate method?



Say i have a method that does some low-level IO and may throw an IOException, and i have a method foo() that calls the low-level IO method several times. Does it make sense to do the exception-handling in a 3rd method like this:



 public void foo() throws MyCheckedException 
// some stuff
goDoSomeIO(path1)
// some other stuff
goDoSomeIO(path2)
// some more stuff
goDoSomeIO(path3)



private String goDoSomeIO(String filePath) throws MyCheckedException
try
doSomeIO(filePath);
catch (IOException ioe)
LOG.error("Io failed at: " + filePath);
throw new MyCheckedException("Process failed because io failed", ioe)



private String doSomeIO(String filepath) throws IOException
//io stuff



I find this is more readable than it would be if the doSomeIO method did its own exception handling, or if the exception handling happend in foo.










share|improve this question
























  • it's a matter of style and it depends on the situation

    – firephil
    Mar 27 at 15:37













2












2








2


1






Is it an anti-pattern to handle exception in a separate method?



Say i have a method that does some low-level IO and may throw an IOException, and i have a method foo() that calls the low-level IO method several times. Does it make sense to do the exception-handling in a 3rd method like this:



 public void foo() throws MyCheckedException 
// some stuff
goDoSomeIO(path1)
// some other stuff
goDoSomeIO(path2)
// some more stuff
goDoSomeIO(path3)



private String goDoSomeIO(String filePath) throws MyCheckedException
try
doSomeIO(filePath);
catch (IOException ioe)
LOG.error("Io failed at: " + filePath);
throw new MyCheckedException("Process failed because io failed", ioe)



private String doSomeIO(String filepath) throws IOException
//io stuff



I find this is more readable than it would be if the doSomeIO method did its own exception handling, or if the exception handling happend in foo.










share|improve this question














Is it an anti-pattern to handle exception in a separate method?



Say i have a method that does some low-level IO and may throw an IOException, and i have a method foo() that calls the low-level IO method several times. Does it make sense to do the exception-handling in a 3rd method like this:



 public void foo() throws MyCheckedException 
// some stuff
goDoSomeIO(path1)
// some other stuff
goDoSomeIO(path2)
// some more stuff
goDoSomeIO(path3)



private String goDoSomeIO(String filePath) throws MyCheckedException
try
doSomeIO(filePath);
catch (IOException ioe)
LOG.error("Io failed at: " + filePath);
throw new MyCheckedException("Process failed because io failed", ioe)



private String doSomeIO(String filepath) throws IOException
//io stuff



I find this is more readable than it would be if the doSomeIO method did its own exception handling, or if the exception handling happend in foo.







java exception anti-patterns software-quality






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 27 at 15:26









IvanaIvana

2601 silver badge15 bronze badges




2601 silver badge15 bronze badges















  • it's a matter of style and it depends on the situation

    – firephil
    Mar 27 at 15:37

















  • it's a matter of style and it depends on the situation

    – firephil
    Mar 27 at 15:37
















it's a matter of style and it depends on the situation

– firephil
Mar 27 at 15:37





it's a matter of style and it depends on the situation

– firephil
Mar 27 at 15:37












2 Answers
2






active

oldest

votes


















2














I frequently see code that handles exceptions of lower level methods at a higher level, regardless if the lower level is just one method or several.



That's quite common and is due to segregated concerns: Low level stuff takes care of pushing files around, high level stuff catches exceptions to determine if a complex operation worked or not. I don't think there's anything wrong with putting the handling of IO and handling of IO in different methods. (I'd try to give them some name, that explains the purpose however. I'm not a fan of goDoWhatever & doWhatever)






share|improve this answer



























  • Oops, sorry, was reading too fast. Just saw the log. Will edit my answer.

    – froh42
    Mar 27 at 15:48












  • Thanks, +1 for 'give it a name that explains the purpose'.

    – Ivana
    Mar 27 at 16:02


















2














The general rule of catching [checked] exception is to do it when you can recover from the 'exceptional' situation that occurred. If you can't recover from the exception here, let it bubble up to a level at which it can be recovered. For example, notify the user the selected file is unreadable and allow the user to select a file again. Or to send a 404 'page' to the requester when the actually requested page doesn't exist.



Effective Java, Item 58



A commonly used exception to this rule is to catch, do some trivial non-recovering work (like logging) and rethrow the exception (possibly wrapped). I see nothing wrong with your approach.



It's actually a pro-pattern to add extra details to the exception and rethrowing it.






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%2f55380871%2fexception-handling-in-separate-method-for-readability%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









    2














    I frequently see code that handles exceptions of lower level methods at a higher level, regardless if the lower level is just one method or several.



    That's quite common and is due to segregated concerns: Low level stuff takes care of pushing files around, high level stuff catches exceptions to determine if a complex operation worked or not. I don't think there's anything wrong with putting the handling of IO and handling of IO in different methods. (I'd try to give them some name, that explains the purpose however. I'm not a fan of goDoWhatever & doWhatever)






    share|improve this answer



























    • Oops, sorry, was reading too fast. Just saw the log. Will edit my answer.

      – froh42
      Mar 27 at 15:48












    • Thanks, +1 for 'give it a name that explains the purpose'.

      – Ivana
      Mar 27 at 16:02















    2














    I frequently see code that handles exceptions of lower level methods at a higher level, regardless if the lower level is just one method or several.



    That's quite common and is due to segregated concerns: Low level stuff takes care of pushing files around, high level stuff catches exceptions to determine if a complex operation worked or not. I don't think there's anything wrong with putting the handling of IO and handling of IO in different methods. (I'd try to give them some name, that explains the purpose however. I'm not a fan of goDoWhatever & doWhatever)






    share|improve this answer



























    • Oops, sorry, was reading too fast. Just saw the log. Will edit my answer.

      – froh42
      Mar 27 at 15:48












    • Thanks, +1 for 'give it a name that explains the purpose'.

      – Ivana
      Mar 27 at 16:02













    2












    2








    2







    I frequently see code that handles exceptions of lower level methods at a higher level, regardless if the lower level is just one method or several.



    That's quite common and is due to segregated concerns: Low level stuff takes care of pushing files around, high level stuff catches exceptions to determine if a complex operation worked or not. I don't think there's anything wrong with putting the handling of IO and handling of IO in different methods. (I'd try to give them some name, that explains the purpose however. I'm not a fan of goDoWhatever & doWhatever)






    share|improve this answer















    I frequently see code that handles exceptions of lower level methods at a higher level, regardless if the lower level is just one method or several.



    That's quite common and is due to segregated concerns: Low level stuff takes care of pushing files around, high level stuff catches exceptions to determine if a complex operation worked or not. I don't think there's anything wrong with putting the handling of IO and handling of IO in different methods. (I'd try to give them some name, that explains the purpose however. I'm not a fan of goDoWhatever & doWhatever)







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 27 at 15:48

























    answered Mar 27 at 15:37









    froh42froh42

    3,9556 gold badges26 silver badges40 bronze badges




    3,9556 gold badges26 silver badges40 bronze badges















    • Oops, sorry, was reading too fast. Just saw the log. Will edit my answer.

      – froh42
      Mar 27 at 15:48












    • Thanks, +1 for 'give it a name that explains the purpose'.

      – Ivana
      Mar 27 at 16:02

















    • Oops, sorry, was reading too fast. Just saw the log. Will edit my answer.

      – froh42
      Mar 27 at 15:48












    • Thanks, +1 for 'give it a name that explains the purpose'.

      – Ivana
      Mar 27 at 16:02
















    Oops, sorry, was reading too fast. Just saw the log. Will edit my answer.

    – froh42
    Mar 27 at 15:48






    Oops, sorry, was reading too fast. Just saw the log. Will edit my answer.

    – froh42
    Mar 27 at 15:48














    Thanks, +1 for 'give it a name that explains the purpose'.

    – Ivana
    Mar 27 at 16:02





    Thanks, +1 for 'give it a name that explains the purpose'.

    – Ivana
    Mar 27 at 16:02













    2














    The general rule of catching [checked] exception is to do it when you can recover from the 'exceptional' situation that occurred. If you can't recover from the exception here, let it bubble up to a level at which it can be recovered. For example, notify the user the selected file is unreadable and allow the user to select a file again. Or to send a 404 'page' to the requester when the actually requested page doesn't exist.



    Effective Java, Item 58



    A commonly used exception to this rule is to catch, do some trivial non-recovering work (like logging) and rethrow the exception (possibly wrapped). I see nothing wrong with your approach.



    It's actually a pro-pattern to add extra details to the exception and rethrowing it.






    share|improve this answer































      2














      The general rule of catching [checked] exception is to do it when you can recover from the 'exceptional' situation that occurred. If you can't recover from the exception here, let it bubble up to a level at which it can be recovered. For example, notify the user the selected file is unreadable and allow the user to select a file again. Or to send a 404 'page' to the requester when the actually requested page doesn't exist.



      Effective Java, Item 58



      A commonly used exception to this rule is to catch, do some trivial non-recovering work (like logging) and rethrow the exception (possibly wrapped). I see nothing wrong with your approach.



      It's actually a pro-pattern to add extra details to the exception and rethrowing it.






      share|improve this answer





























        2












        2








        2







        The general rule of catching [checked] exception is to do it when you can recover from the 'exceptional' situation that occurred. If you can't recover from the exception here, let it bubble up to a level at which it can be recovered. For example, notify the user the selected file is unreadable and allow the user to select a file again. Or to send a 404 'page' to the requester when the actually requested page doesn't exist.



        Effective Java, Item 58



        A commonly used exception to this rule is to catch, do some trivial non-recovering work (like logging) and rethrow the exception (possibly wrapped). I see nothing wrong with your approach.



        It's actually a pro-pattern to add extra details to the exception and rethrowing it.






        share|improve this answer















        The general rule of catching [checked] exception is to do it when you can recover from the 'exceptional' situation that occurred. If you can't recover from the exception here, let it bubble up to a level at which it can be recovered. For example, notify the user the selected file is unreadable and allow the user to select a file again. Or to send a 404 'page' to the requester when the actually requested page doesn't exist.



        Effective Java, Item 58



        A commonly used exception to this rule is to catch, do some trivial non-recovering work (like logging) and rethrow the exception (possibly wrapped). I see nothing wrong with your approach.



        It's actually a pro-pattern to add extra details to the exception and rethrowing it.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 27 at 15:52

























        answered Mar 27 at 15:35









        Mark JeronimusMark Jeronimus

        5,9352 gold badges22 silver badges39 bronze badges




        5,9352 gold badges22 silver badges39 bronze badges






























            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%2f55380871%2fexception-handling-in-separate-method-for-readability%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권, 지리지 충청도 공주목 은진현