Checked vs Unchecked exception

后端 未结 6 560
抹茶落季
抹茶落季 2020-11-27 06:49

I\'ve studied that: With an unchecked exception, however, the compiler doesn\'t force client programmers either to catch the exception or declare it in a throws clause. In f

6条回答
  •  不知归路
    2020-11-27 07:33

    Unchecked exceptions are those that extend RuntimeException class. Compiler will never force you to catch such exception or force you to declare it in the method using throws keyword. All other exception types (that do not extend RuntimeException) are checked and therefore must be declared to be thrown and/or catched.

    Checked exceptions are used when you want the caller of your method (i.e the user of your API) to explicitly handle the exceptional case in your API. Checked exceptions are declared when you believe the call will be able to do something meaningful with that exceptional case, like retrying the call, rolling changes back or converting it into some user-readable error message.

    If you believe that there is nothing useful the call can do about the exception (especially when it represents a bug, or a wrong usage of your API), then the exception should be unchecked. Also, an API with too many checked exceptions can be annoying to program with (e.g. try using java reflection API=)

提交回复
热议问题