Need authoritative source for why you shouldn't throw or catch java.lang.Exception

后端 未结 9 1055
无人及你
无人及你 2020-12-19 09:27

I\'ve got a coding standards meeting in just over an hour and I need a quick answer to this one.

Common wisdom among experienced Java programmers is that you don\'t

相关标签:
9条回答
  • 2020-12-19 10:06

    it's a long article but this proposes you:

    1. use checked exceptions when the client expects this error to occur regularly and must handle it (ex: user-entered data did not pass validation)
    2. use unchecked exceptions for unexpected conditions (ex: DB server went down)

    In theory, #1 (expected errors) should have their own exception type, and the only place that should catch a #2 (a RuntimeException) is some type of top-level handler that catches the exception, logs it, and shows the user an error message, and even here, you should probably catch Throwable to make sure any uncaught exceptions are handled.

    Following these guidelines, you shouldn't catch Exception since it doesn't fit either of the above criteria (meaning, it's not a RuntimeException and it's not a specialized Exception sublcass to indicate an expected error).

    0 讨论(0)
  • 2020-12-19 10:07

    If you have a copy of Josh Bloch's Effective Java to hand, I know he covers exception handling in a fair bit of detail there. I don't have access to it at present so I can't summarise it or give you page references, but I'm pretty sure he's got some good arguments for not catching java.lang.Exception.

    0 讨论(0)
  • 2020-12-19 10:13

    Here is a very insightful article

    Summary:

    1. Use checked exceptions for rare but valid contingencies that relate to the purpose of your code. Client code should know how to handle these.

    2. Use unchecked exceptions for faults that shouldn't happen but do. (Server down, classpath misconfigured, SQL syntax error, etc.) The IT guy who manages the server, or the developer who just passed bad SQL to prepareStatement() should know how to fix these problems. Faults should propagate up to the logging layer so the info doesn't get lost.

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