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

后端 未结 9 1094
无人及你
无人及你 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).

提交回复
热议问题