Best practice for Java exception handling

后端 未结 2 1087
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 11:33

I wrote the following code recently; it uses a lot of exception handling. I think it makes the code look very unreadable. I could shorten the code by catching generic except

相关标签:
2条回答
  • 2020-12-14 12:31

    First, unless you have very good reason, never catch RuntimeException, Exception or Throwable. These will catch most anything that is thrown, and Throwable will catch everything, even those things you're not meant to catch, like OutOfMemoryError.

    Second, avoid catching runtime exceptions unless it directly impedes with the critical operation of your program. (But seriously, if anyone sees you catch a NullPointerException, they are within their full rights to call you out on it.) The only exceptions you should be bothering with are those that you are required to handle. Out of your list of exceptions, the only one you should bother with is IOException. The rest are the result of not enough tests, or sloppy coding; those shouldn't occur in the normal run time of your application.

    Third, in Java 7, you have the ability to do a multi-catch statement for your exceptions, if the exceptions are mutually exclusive. The example linked does a good job of explaining it, but if you were to encounter code that threw both an IOException and an SQLException, you could handle it like this:

    try {
        // Dodgy database code here
    catch (IOException|SQLException ex) {
        logger.log(ex);
        throw ex;
    }
    

    This cleans things up a bit, as you don't have unwieldy and huge chains of exceptions to catch.

    0 讨论(0)
  • 2020-12-14 12:32

    First of all the problem with "best practice" advice is that it tends to over-simplify the question and the answer. Then someone (like yourself) comes along and notices that it is contradictory.

    IMO, best practice is to take "best practice" advice and people who regularly use that phrase with a healthy level of suspicion. Try to understand the real issues yourself, and reach your own conclusions ... rather than just relying someone else to tell you what is "best practice".


    So what's the problem here? It is this statement:

    but I also heard that catching generic exception is not a good coding practice.

    In fact, it is not normally good coding practice to catch generic exceptions like Exception. But it is the right thing to do in some circumstances. And your example is one where it is appropriate.

    Why?

    Well lets look a case where catching Exception is a bad idea:

        public void doSomething(...) {
            try {
                doSomethingElse(...);
            } catch (Exception ex) {
                // log it ... and continue
            }
        }
    

    Why is that a bad idea? Because that catch is going to catch and handle unexpected exceptions; i.e. exceptions that you (the developer) did not think were possible, or that you did not even consider. That's OK ... but then the code logs the exception, and continues running as if nothing happened.

    That's the real problem ... attempting to recover from an unexpected exception.

    The (so-called) "best practice" advice to "never catch generic exceptions" deals with the issue, but in a crude way that doesn't deal with the edge cases. One of the edge cases is that catching (and logging) a generic exception is OK if you then immediately shut the application down ... like you are doing.

        public void main(...) {
            try {
                // ...
            } catch (Exception ex) {
                // log exception
                System.err.println("Fatal error; see log file");
                System.exit(1);
            }
        }
    

    Now contrast that with the (supposedly) good practice version in your question. What is the difference?

    1. Your version produces more user friendly / less alarming diagnostics ... up to a point.
    2. Your version is significantly more code.
    3. Your version is unhelpful to someone trying to diagnose the problem because the stacktraces are not recorded.

    And the counterpoints to 1 and 2 are:

    1. You can spend limitless time honing the "user friendly" diagnostics for an application, and still fail to help the kind of user who can't or won't understand ...
    2. It also depends on who the typical user is.

    As you can see, this is far more nuanced than "catching generic exceptions is bad practice".

    0 讨论(0)
提交回复
热议问题