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 explicitly caught or re-throwed in the code through try-catch. If you don't need to handle the exception, you can simply throw the exception again. 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.

Choose checked or unchecked exceptions?

Some Java books recommend using checked exception handlers for all recoverable exceptions and unchecked exceptions for unrecoverable errors. But in fact, most of the Java exceptions inherited from RuntimeException can also be recovered in the program, such as NullPointerException, IllegalArgumentExceptions, exceptions other than 0, etc., can be captured and processed to make the program continue to run. Only some special cases will break the execution of the program, such as reading the configuration file at startup, if the configuration file does not exist or there is a serious error, the program has to exit.

Here are some arguments for and against checked exceptions:

  1. The compiler enforces catching or throwing unchecked exceptions so that developers always remember to handle exceptions.
  2. A method that throws a checked exception must declare throws, and throws become a part of the method or interface, which brings inconvenience to the exception of subsequent versions of adding or modifying methods.
  3. Unchecked exceptions do not need to be handled explicitly but make exception handling more difficult.
  4. When calling a method with a checked exception, it is necessary to handle the exception of this method, which confuses the upper-level caller code.

 

It is up to you to decide whether to choose checked or unchecked. It is difficult to say which one is right, and vice versa. Among the more popular languages ​​at present, Java seems to be the only language that supports checked exceptions, and all other languages ​​only have unchecked exceptions.

 

 

 

 

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

Under normal circumstances 

@Transactional  does not perform transaction rollback for checked exceptions; if you need to rollback, you need to add

@Transactional (rollbackFor= Exception . class ) can take effect;

Guess you like

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