Java checked and unchecked exception Tutorial

In this section, we will learn what the checked and unchecked exceptions are and how they work in Java.

Prerequisites: exceptions in general and try catch blocks.

Java Exception Hierarchy

Hierarchy of Exception in Java

Exceptions are broadly categorized into two sections:

  • checked exceptions: compile time exception in Java
  • unchecked exceptions: runtime exception in Java

What is checked exception in Java? (Compile time exception in Java)

When the compiler wants to compile a program, other than making sure that the syntax of the program is correct, it will also check the source code for a set of exceptions and sees if the source code has the potential to throw those types of exceptions! This type of compile time checking is called checked exception.

For example, if your program is about opening a file and reading its content, intrinsically, this program has the potential of getting a wrong address of a file! For example, a user might put the address of a file that does not exist!

These types of exceptions have external reasons and it’s not something that we as developers can stop from happening!

For this reason, the compiler checks the source code and insists on using exception handlers in that program when it sees the potential of occurring such exceptions in the program.

These types of exceptions that the compiler will check at compile time are called checked exceptions.

Here’s the list of exceptions that will be checked in a program by the compiler:

Exceptions of type Throwable, the Exception class and its subclasses with the exclusion of the RuntimeException class and its subclasses.

Example: handling checked exception in Java

import java.io.FileInputStream;

public class Simple {

    public static void main(String[] args) {
        FileInputStream fileInputStream = new FileInputStream("sdfs");
    }
}

Output:

Error:(9, 43) java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown

Here we’ve got a compile time error because we used the `FileInputStream` class to work with files. The compiler here strongly believes that working with files can run into multiple types of exceptions at runtime. For example, here because we set an address of a file as the argument of the `FileInputStream`, the compiler thinks that this address might not point to a file. So it is insisting that we should handle the `FileNoteFoundException` exception that might happen in the program.

Let’s fix this problem by adding a `try-catch` to the program and handle this exception:

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Simple {

    public static void main(String[] args) {
        try {
            FileInputStream fileInputStream = new FileInputStream("sdfs");
        } catch (FileNotFoundException e) {
            System.out.println("Exception occurred and here's the reason: "+ e.getMessage());
        }
    }
}

Output:

Exception occurred and here's the reason: sdfs (The system cannot find the file specified)

Now that we handled this exception, we won’t get the compile time error anymore and if any exception occurs, that will be at runtime.

What is an unchecked exception in Java? (Runtime exception in Java)

On the other hand, there are types of exceptions that might occur in a program, but the compiler won’t check the source code for these types of exception at compile time!

For example, in a program, it might end up using so much of the computer’s stack memory that we get `StackOverFlowError` exception. This is not some type of error that the compile can see before runtime and so it won’t check the source code for such type of exception!

In short, those types of exceptions that cannot be seen at compile time and only when the program is running, fell in this category.

Here’s the list of unchecked exceptions:

Exceptions of type Error and all of its subclasses, the RuntimeException class and all its subclasses.

Example: handling unchecked exception in Java

public class Simple {

    public static void main(String[] args) {
        try {
            int res = 40/0;
            System.out.println(res);
        } catch ( ArithmeticException exception) {
            System.out.println(exception.getMessage());
        }
    }
}

Output:

/ by zero

The `ArithmeticException` is a subclass of the `RuntimeException` class and so the compiler won’t check this exception at compile time. So the error that we’ve got here occurred at runtime while the program was running.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies