About exception types

Java exceptions are divided into two types, checked exceptions and unchecked exceptions, another called exceptions and errors.

Simply put, checked is recoverable during execution, while unchecked exceptions are errors that cannot be handled.

checked exception:

  • Indicates invalid, not predictable in the program. Such as invalid user input, file does not exist, network or database link error. These are all external reasons, and none of them can be controlled within the program.
  • Must be handled explicitly in the code. For example, try-catch block processing, or add a throws description to the method where it is located, and throw the exception to the upper layer of the call stack.
  • Inherited from java.lang.Exception (except java.lang.RuntimeException).

unchecked exception:

  • Indicates an error, a logical error in the program. Is a subclass of RuntimeException, such as IllegalArgumentException, NullPointerException and IllegalStateException.
  • There is no need to explicitly catch unchecked exceptions in your code for handling.
  • Inherited from java.lang.RuntimeException (and java.lang.RuntimeException inherited from java.lang.Exception).

The checked exception in Java needs to be caught or re-throwed explicitly through try-catch in the code. If you don't need to handle the exception, you can simply re-throw the exception. This kind of exception has some shortcomings, and many people are used to it. Write an empty catch block directly in the code, which not only makes the code somewhat redundant and "ugly", but also brings trouble to debugging and increases the difficulty of code maintenance. So some people say that checked makes the code verbose, and empty catch blocks are meaningless, so checked exceptions should be removed from the Java standard. For example, there is no concept of checked exceptions in C#, and C# does not enforce explicit catch exceptions.

The reason why Java exceptions are divided into these two types should be due to the following considerations:

Checked exceptions can help developers realize which line is likely to throw an exception, because Java's API already states which method calls may throw exceptions. If you don't do the compilation, you can't pass it. To some extent, this approach can avoid some errors in the program.

two simple examples

1. checked exception

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
 
public class Main {
 
public static void main(String[] args) {
 
File f = new File( "C:\test.txt" );
FileReader r = new FileReader(f); //A
BufferedReader br = new BufferedReader(r);
br.readLine(); //B
br.close(); //C
 
}
 
}

This code doesn't compile because lines A, B, and C throw IOExceptions. You must put this code in a try-catch block, or add throws IOException to the main method to compile.

2. Unchecked exception

1
2
3
4
5
6
7
8
9
10
11
public class Main {
 
public static void main(String[] args) {
 
int a = 0 ;
int b = 100 ;
int c = b/a;
 
}
 
}

It can be compiled, but the execution will report an error

Exception in thread “main” java.lang.ArithmeticException: / by zero
at Main.main(Main.java:13)

ArithmeticException is an unchecked exception.

custom exception

1. checked exception

Custom exception class InvalidUrlException

1
2
3
4
5
public class InvalidUrlException extends Exception {
public InvalidUrlException(String s){
super (s);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Main {
 
public static void getRemoteData(String url) throws InvalidUrlException{
if (isValidUrl(url)){
//获取远程数据
}
else
throw new InvalidUrlException( "Invalid URL: " + url);
}
 
public static boolean isValidUrl(String url){
.... //验证URL是否有效
}
public static void main(String[] args) {
getRemoteData(args[ 0 ]);
}
}

If you call getRemoteData in the main method, there are two ways, one is try-catch, the other is to add throws InvalidUrlException directly to main.

2. Unchecked exception

If you change InvalidUrlException to extends RuntimeException,

1
2
3
4
5
public class InvalidUrlException extends Exception {
public InvalidUrlException(String s){
super (s);
}
}

Then main does not need to add throws or try-catch.

选择checked还是unchecked异常?

一些Java书籍建议使用checked异常处理程序中所有可恢复的异常,而用unchecked异常作为无法恢复的错误。但是实际上那些继承自RuntimeException的Java异常大多也可以在程序中恢复的,比如NullPointerException、IllegalArgumentExceptions、除0异常等等都可以通过捕获处理使程序继续运行。只有一些特殊情况会破坏程序的执行,比如启动的时候读取配置文件,如果配置文件不存在或者有严重错误,程序只好退出。

以下是是支持和反对checked异常的一些观点:

  1. 编译器强制捕获或者抛出unchecked异常使开发人员时刻记着要处理异常。
  2. 抛出checked异常的方法必须声明throws,throws成为了方法或者接口的一部分,给后续版本增加或者修改方法的异常带来不便。
  3. unchecked异常不需要显式地处理反而使异常处理变的困难。
  4. 调用checked异常的方法,就必须处理这个方法的异常,这使得上层的调用者代码混乱。

 

选择checked还是unchecked都是由你自己决定的,很难说哪种就一定正确,反之就一定错误。目前比较流行的语言中,Java似乎是唯一支持checked异常的语言,其他语言都只有unchecked异常。

 

 

 

 

////////////////////////////////////////////////////////////////////////////////////

正常情况下 

@Transactional 对于checked的异常不进行事务回滚;如果需要回滚,需要加上

@Transactional(rollbackFor=Exception.class) 才能生效;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326441029&siteId=291194637