Guide to Checked and Unchecked Exceptions in Java.
An exception is an unexpected event during program execution that messes up the normal flow of instructions often resulting in crashing the application.
In my previous article, I discussed how to handle Exceptions in Java.
In this one, let’s explore the types of exceptions in Java.
In Java, exceptions are basically categorised into two main types.
- Checked exceptions
- Unchecked exceptions
Checked Exceptions
Checked exceptions in Java are the ones that the compiler requires programmers to handle explicitly. If you have a checked exception in your code in Java, you must handle it before you can successfully compile the program. Java won’t let you compile the code if you don’t handle the checked exception.
Suppose you want to display the first line of a text file using Java. The given incomplete Java code is supposed to set up a BufferedReader to read the initial line from the specified file (filePath) given as a parameter. Then it captures the first line in a variable called firstLine
, and after that, it closes the BufferedReader to free up resources, finally, it returns the first line of the file.
public static String readFirstLine(String filePath) {
//incomplete code
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String firstLine = reader.readLine();
reader.close();
return firstLine;
}
Notice that the code editor is giving a warning about an unhandled exception even before compiling. In this state, you cannot compile the code until you handle the exception yourself. This is the nature of the Checked Exception. Java explicitly requires that you handle this exception before your program runs.
Handling the exception
There are two ways to handle the exception.
- Wrap the code inside a try-catch block to handle the exception.
public static String readFirstLine(String filePath) {
try {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String firstLine = reader.readLine();
reader.close();
return firstLine;
} catch (IOException fe) {
System.out.println(fe.getMessage());
return null;
}
}
2. Throw an exception in the method signature
public static String readFirstLine(String filePath) throws IOException{
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String firstLine = reader.readLine();
reader.close();
return firstLine;
}
However, If you throw an exception like this from the method, you need to handle it where you call the method using either a try-catch block or throwing the exception.
Unchecked Exceptions
Unchecked exceptions, unlike checked ones, don’t have the same compile-time constraints. You can compile and run your code without issues. However, you might encounter this exception while the application is running.
So let's say that there’s a function called getUpperCaseText
that takes a String as an argument and returns its uppercase version.
public static void main(String[] args) {
System.out.println(getUpperCaseText("Hello World"));
}
public static String getUpperCaseText(String text){
return text.toUpperCase();
}
This function operates normally, but it throws an error if the input text is null
when it runs.
Unlike before, even if you deliberately set the text
to null
in the code, VS Code doesn’t provide a warning about NullPointerException
before it complies. That’s because NullPointerException is an unchecked exception. The given incomplete Java code is supposed to set up a BufferedReader to read the initial line from the specified file (filePath) given as a parameter. Then it captures the first line in a variable called firstLine, and after that, it closes the BufferedReader to free up resources, finally, it returns the first line of the file.Java doesn’t check for unchecked exceptions before compiling the code.
However, As a developer, you need to be prepared to handle such unchecked exceptions in your code so your program doesn’t crash unexpectedly.
public static void main(String[] args) {
try {
System.out.println(getUpperCaseText(null));
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static String getUpperCaseText(String text){
return text.toUpperCase();
}
How does Java know?
So the question is which exceptions are unchecked or checked and how does Java determine what kind of exceptions are they?
As you can see below, In Java, checked and unchecked exceptions are categorized based on their class hierarchy. Checked exceptions in Java are those that extend the Exception class directly. So they need to be addressed before compiling. Unchecked exceptions in Java, on the other hand, extend the RuntimeException class.
So in conclusion Understanding the difference between checked and unchecked exceptions is very useful when writing robust Java code. Checked exceptions act as guards, ensuring potential issues are addressed before the program is compiled, while unchecked exceptions offer flexibility in handling unexpected runtime errors.
So when you are writing a Java application, consider your application’s specific requirements and choose the exception type that aligns best with your development goals.
Happy Coding!!!