Summary: In this tutorial, you will learn about Java checked and unchecked exceptions and the differences between them.
Java exceptions are classes. Exceptions fall into two main types:
- Checked exceptions
- Unchecked exceptions
Note that if either checked or unchecked exception occurs, the problem will crash. Let’s explore each type of exception and understand the differences between them.
Java checked exceptions
Checked exceptions are exceptions that the compiler will issue an error if you do not handle them explicitly in your code using the try catch statement:
try{
// Code that throws a checked exception
}catch(CheckedExceptionType e){
// Code to handle the checked exception
}
Code language: Java (java)
Or declare them in the method signature:
public void methodName() throws CheckedExceptionType {
// Code that throws CheckedExceptionType
}
Code language: Java (java)
Checked exceptions represent errors that you cannot control such as reading from a file that doesn’t exist or making a connection to a database server that is currently down.
In Java, the checked exception classes are all subclasses of Throwable
class other than RuntimeException
class and its subclasses and Error
class and its subclasses.
For example, the FileNotFoundException
, SQLException
, and ConnectException
classes are checked exceptions.
The following diagram shows the checked exception classes in the exception class hierarchy:
Java checked exception example
The following program attempts to read a text file line by line and writes each line on the screen:
import java.io.BufferedReader;
import java.io.FileReader;
public class App {
public static void processFile(String filename) {
var reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
public static void main(String[] args) {
var filename = "src/readme.txt";
processFile(filename);
}
}
Code language: Java (java)
The Java compiler issues three errors:
- The
FileReader
throws aFileNotFoundException
. - The
readerLine()
method of thereader
object throws anIOException
. - The close() method of the reader object also throws an
IOException
.
Because both FileNotFoundException
and IOException
are checked exceptions, the Java compiler requires you to handle explicitly or declare them in the processFile()
method.
The following shows how to use the try catch finally statement to handle the FileNotFoundException
and IOException
in the processMethod()
:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class App {
public static void processFile(String filename) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("File not found:" + e.getMessage());
} catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
public static void main(String[] args) {
var filename = "src/readme.txt";
processFile(filename);
}
}
Code language: Java (java)
Another way to fix the issue is to propagate the exception by declaring them in the processFile()
method’s signature and handle the exceptions in the main()
method:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class App {
public static void processFile(String filename) throws IOException {
var reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
public static void main(String[] args) {
var filename = "src/readme.txt";
try {
processFile(filename);
} catch (FileNotFoundException e) {
System.out.println("File not found:" + e.getMessage());
} catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
}
}
}
Code language: Java (java)
Because the FileNotFoundException
class is a subclass of the IOException
class, you need to throw the IOException
, which is more general than the FileNotFoundException
class.
In the main()
class, you can catch the IOException
only. Or you can also catch a more specific exception of the IOException
class which is the FileNotFoundException
class.
Java unchecked exceptions
Unchecked exceptions are exceptions that the compiler does not require you to handle in your code or declare in the method. They represent programming errors that you can prevent via good coding practices.
The unchecked exception classes are the ones that extend the RuntimeException
class, for example, ArithmeticException
and ArrayIndexOutOfBoundsExceptions
. They are often referred to as runtime exceptions.
The following shows the unchecked exception classes in the exception class hierarchy:
Java unchecked exception example
The following program declares an array of five integers and attempts to access the element at index 5. Therefore, it encounters an ArrayIndexOutOfBoundsException
exception:
public class App {
public static void main(String[] args) {
int[] scores = {5, 3, 4, 2, 1};
int index = 5;
System.out.println(scores[index]); // exception
}
}
Code language: Java (java)
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 5
Code language: Java (java)
In this example, the Java compiler doesn’t require you to catch the exception explicitly like checked exceptions. And you can fix the error by checking the index of the array element before accessing it as shown in the following code:
public class App {
public static void main(String[] args) {
int[] scores = {5, 3, 4, 2, 1};
int index = 5;
if (index >= 0 && index < scores.length) {
System.out.println(scores[index]); // exception
} else {
System.out.printf("The valid range of the index is (0,%d)", index - 1);
}
}
}
Code language: Java (java)
Output:
The valid range of the index is (0,4)
Code language: Java (java)
Java checked exception vs. unchecked exceptions
The following table summaries the differences between checked and unchecked exceptions:
Characteristic | Checked Exceptions | Unchecked Exceptions |
---|---|---|
Compilation Requirement | Must catch the checked exceptions explicitly or declare them in the method. | No need to declare or catch unchecked exceptions explicitly. |
Inheritance Hierarchy | The subclasses of Throwable class except the RuntimeException class and its subclasses and Error class and its subclasses. | The RuntimeException class and its subclasses. |
When They Occur | Represent external errors beyond your control, such as I/O errors. | Indicate programming errors, such as array index out of bounds. |
Examples | IOException | NullPointerException |
Common Use Cases | Used for situations where recovery or graceful error handling is possible. | Used for critical errors, or when explicit handling is not possible. |
Summary
- Java has two types of exceptions: checked and unchecked.
- Java compiler raises an error if check exceptions are not handled explicitly or propagated properly.
- Java compiler does not require handling unchecked exceptions because they can be fixed through good coding practices.