When to choose checked and unchecked exceptions

前端 未结 18 2620
南方客
南方客 2020-11-22 04:13

In Java (or any other language with checked exceptions), when creating your own exception class, how do you decide whether it should be checked or unchecked?

My inst

18条回答
  •  自闭症患者
    2020-11-22 04:54

    We have to distinguish these two types of exception based on whether it is programmer error or not.

    • If an error is a programmer error, it must be an Unchecked Exception. For example: SQLException/IOException/NullPointerException. These exceptions are programming errors. They should be handled by programmer. While in JDBC API, SQLException is Checked Exception, In Spring JDBCTemplate it is an Unchecked Exception.Programmer doesn't worry about SqlException, when use Spring.
    • If an error is not a programmer error and the reason is coming from external, it must be a Checked Exception. For example: if the file is deleted or file permission is changed by someone else, It should be recovered.

    FileNotFoundException is good example to understand subtle differences. FileNotFoundException is thrown in case file is not found. There are two reason for this exception. If the file path is defined by developer or taking from end user via GUI it should be an Unchecked Exception. If the file is deleted by someone else, it should be a Checked Exception.

    Checked Exception can be handled in two ways. These are using try-catch or propagate the exception. In case of propagation of exception, all methods in call stack will be tightly coupled because of exception handling. That's why, we have to use Checked Exception carefully.

    In case you develop an layered enterprise system, you have to choose mostly unchecked exception to throw, but don't forget to use checked exception for the case you cannot do anything.

提交回复
热议问题