This discussion is archived
11 Replies Latest reply: Oct 15, 2012 1:14 PM by EJP RSS

Exception Handling

SRAVZ Newbie
Currently Being Moderated
Hi All

Need you comments on exception handling and also suggest any recommended approach, Its just a common utility method i m writing

public static void test(int j) throws NumberFormatException, Exception{
          try{
               int i = 247912900;
               System.out.println(i/j);
          }catch(NumberFormatException nex){
               nex.printStackTrace();
               throw nex;
          }catch(Exception ex){
               ex.printStackTrace();
               throw ex;
          }
     }
  • 1. Re: Exception Handling
    abillconsl Explorer
    Currently Being Moderated
    As Joshua Bloch stated, "deciding which exception to resuse is not always an exact science". In your case, it might be better to catch the NumberFormatException but pass on an IllegalArgumentException, so that the caller at the higher level has a better idea of why the call failed. Adding additional information to the thrown exception will likely help.
  • 2. Re: Exception Handling
    aksarben Journeyer
    Currently Being Moderated
    As a general rule, don't catch an exception unless you do something with it. Your example at least outputs it, which is good. What's really bad is this awful snippet you see way too often:
    catch (Exception ex) {
    }
    This merely hides the exception, which is bound to cause head scratching later on.
  • 3. Re: Exception Handling
    jtahlborn Expert
    Currently Being Moderated
    this exception "handling" is basically the "log and throw" pattern, which is generally referred to as an "anti-pattern", as in, "you shouldn't do it". it ends up generating very confusing logs (assuming the code which eventually catches the exception also logs it). one of the few times this pattern is a good idea is if you know that the calling code (over which you have no control) is potentially swallowing a useful exception (this can also be useful in distributed systems where the caller is a remote client to which you do not have access).
  • 4. Re: Exception Handling
    800268 Expert
    Currently Being Moderated
    SRAVZ wrote:
    Need you comments on exception handling and also suggest any recommended approach, Its just a common utility method i m writing
    In you example I would go for:
    /**
     * Divides 247912900 by j and prints the result to System out.
     *
     * @throws ArithmeticException if j == 0
     */
    public static void test(int j) {
      int i = 247912900;
      System.out.println(i/j);
    }
    Of course this utility method makes no sense, but in general if it is not doing anything useful with exception, just let them bubble up. Note that NumberFormatException is never thrown by you example code.
  • 5. Re: Exception Handling
    939520 Explorer
    Currently Being Moderated
    I believe the section on exceptions in the following link does a pretty good job of explaining things:
    http://www.javapractices.com/home/HomeAction.do

    I also suggest reading most of the other links on that page for all kinds of topics on good programming practices.
  • 6. Re: Exception Handling
    EJP Guru
    Currently Being Moderated
    According to whom? Has it been peer-reviewed? Who are the authors? Where is the comment submission mechanism?

    The first place I looked, 'Exceptions and flow control', contains at least two howling errors and a link that doesn't go where it says it goes.

    Just another hobby site.
  • 7. Re: Exception Handling
    939520 Explorer
    Currently Being Moderated
    Oh well, I suppose the authors should have included this in their link: http://kith.org/jimmosk/disclaimer2.html If anyone knows of a good best practices link that is better (and specifically addresses exception handling), please let us know.
  • 8. Re: Exception Handling
    gbishop Newbie
    Currently Being Moderated
    I've been developing for 20 years. Here are my personal best practice recommendations:

    1. I recommend you try to use unchecked exceptions when re-throwing exceptions.
    2. At the top level where you catch exceptions, always log them or print them.
    3. If you are intentionally ignoring a specific exception call the exception variable "ignored", not e or ex, and comment why.
    4. Avoid creating checked exceptions - they are a pain to deal with.
    5. Log the cause of an exception in its message when creating it.
    6. NEVER return from a finally as that will eat any exception.
    7. Have your application extends unchecked exception & make all exceptions your own code throws throw that type of exception for application errors, but use JDK exceptions for logic errors (NPE, IllegalArgumentException etc).

    8. When displaying an error to a user try to print something friendly to the user.
    9. Print something useful to the programmer in a log.
    10. For html results, put the stack trace in the source of the page if appropriate & scrub usernames, cc#'s, ssn's and passwords!
  • 9. Re: Exception Handling
    gimbal2 Guru
    Currently Being Moderated
    user10739046 wrote:
    I've been developing for 20 years. Here are my personal best practice recommendations:
    People can program for 20 years and still be absolutely oblivious, it is not an argument for people to start listening to you.
    8. When displaying an error to a user try to print something friendly to the user.
    10. For html results, put the stack trace in the source of the page if appropriate & scrub usernames, cc#'s, ssn's and passwords!
    That would be a contradiction if you don't define further what you mean by "source of the page". Does the user see the stacktrace on screen or not? If the user sees it: contradiction.
    4. Avoid creating checked exceptions - they are a pain to deal with.
    Wrong to generalize that, they are slightly more work to deal with. Mork work is not necessarily a pain and should not be a reason to alter the design of the code just to not have to deal with it. Sometimes checked exceptions make sense, when they do you should use them regardless of the added chores (such as adding throws clauses).


    Other than those little things: nice post.
  • 10. Re: Exception Handling
    gbishop Newbie
    Currently Being Moderated
    user10739046 wrote:
    I've been developing for 20 years. Here are my personal best practice recommendations:
    People can program for 20 years and still be absolutely oblivious, it is not an argument for people to start listening to you.

    Tone it down.

    8. When displaying an error to a user try to print something friendly to the user.
    10. For html results, put the stack trace in the source of the page if appropriate & scrub usernames, cc#'s, ssn's and passwords!
    That would be a contradiction if you don't define further what you mean by "source of the page". Does the user see the stacktrace on screen or not? If the user sees it: contradiction.

    This is not a contradiction. You didn't think about what I wrote. You can put the code into a tag that is not displayed on the page, but that is available when you view the page source. The user doesn't see it but the programmer knows its there to be looked for.

    4. Avoid creating checked exceptions - they are a pain to deal with.
    Wrong to generalize that, they are slightly more work to deal with. More work is not necessarily a pain and should not be a reason to alter the design of the code just to not have to deal with it. Sometimes checked exceptions make sense, when they do you should use them regardless of the added chores (such as adding throws clauses).
    Other than those little things: nice post.

    I'm going to disagree. Checked exceptions are NEVER appropriate in line of business application code. They cause concerns to leak from the layers of an application. This is why java's SQL classes are such a pain to deal with and why closeQuietly ans other such utility methods exist.
  • 11. Re: Exception Handling
    EJP Guru
    Currently Being Moderated
    Please, not another checked/unchecked exception war. As to the rest, I've been programming for 41 years and I'm merely sceptical about most attempts to lay down the law about anything in this business, especially when it comes with a 'NEVER'. There are very few NEVERs in this business. And I have a colleague who has been programming for over 45 years and I wouldn't take his recommendation on anything whatsoever.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points