Understand java checked and unchecked exceptions through examples

Time:2020-1-16

Java exceptions are divided into two types: checked and unchecked. The other is called exception and error.

In short, checked can be recovered during execution, while unchecked exception is an unhandled error.

Checked exception:

Indicates invalid, not predictable in the program. For example, invalid user input, file does not exist, network or database link error. These are external reasons, not internal control of the program.

Must be explicitly handled in code. For example, try catch block processing, or add throws to the method to 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 of the program. Are subclasses of runtimeException, such as illegalargumentexception, NullPointerException, and IllegalStateException.

There is no need to explicitly catch unchecked exceptions in the code for processing.

Inherited from java.lang.runtimeexception (and java.lang.runtimeexception inherited from Java. Lang.exception).

The checked exception in Java needs to be explicitly captured or re thrown by try-catch in the code. If you don ‘t need to deal with this exception, you can simply throw it again. This exception has some shortcomings. Many people are used to writing an empty catch block directly in the code, which not only makes the code redundant and “ugly”, but also brings trouble to debugging Added the difficulty of code maintenance. So some people say that checked makes the code lengthy and empty catch blocks meaningless, so checked exceptions should be removed from the Java standard. For example, there is no concept of checked exceptions in C #, and C #, which does not force to catch exceptions explicitly.

Java exceptions can be divided into these two types because of the following considerations:

Checked exceptions help developers realize which lines are likely to have exceptions, because the Java API already shows which methods to call may throw exceptions. If you don’t do processing compilation, you can’t pass. To some extent, this method can avoid some errors of the program.

Two simple examples

1. Checked exception


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 cannot be compiled because lines a, B and C throw IOException. You must put this code in the try catch block or add throws IOException to the main method to compile.

2. Unchecked exception


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

public class InvalidUrlException extends Exception {
public InvalidUrlException(String s){
super(s);
}
}
public class Main {
public static void getRemoteData(String url) throws InvalidUrlException{
if(isValidUrl(url)){
//Get remote data
}
else
throw new InvalidUrlException("Invalid URL: " + url);
}
public static boolean isValidUrl(String url){
... // verify that the URL is valid
}
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 directly add throws invalidurlexception to main.

2. Unchecked exception

If you change invalidurlexception to extends runtimeException


public class InvalidUrlException extends Exception {
public InvalidUrlException(String s){
super(s);
}
}

Then main doesn’t need to add throws or try catch.

Select checked or unchecked exception?

Some java books recommend using all recoverable exceptions in checked exception handlers, and using unchecked exceptions as unrecoverable errors. But in fact, most of the Java exceptions inherited from the runtimeException can also be recovered in the program, such as NullPointerException, illegalargumentexceptions, exception except 0, etc., which can make the program continue to run through capture processing. There are only some special circumstances that can destroy the execution of the program, such as reading the configuration file at startup. If the configuration file does not exist or there are serious errors, the program has to exit.

Here are some views that support and oppose checked exceptions:

The compiler forces an unchecked exception to be caught or thrown so that the developer remembers to handle the exception at all times.

Methods that throw checked exceptions must declare throws, which becomes a part of the method or interface, which brings inconvenience to subsequent versions to add or modify exceptions of methods.

Unchecked exceptions do not need to be handled explicitly, but make exception handling difficult.

When calling the checked exception method, you must handle the exception of this method, which makes the upper caller code confusing.

It’s up to you to choose checked or unchecked. It’s hard to say which one is right, and vice versa. At present, Java seems to be the only language that supports checked exceptions, and other languages only have unchecked exceptions.

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.