Contents

Checked vs Unchecked Exceptions in Java

In this post, we will explore the differences between checked and unchecked exceptions in Java, starting from the basics.

In this article, we will explore the very important topic of exceptions in Java: Checked vs Unchecked exceptions. Let’s start with the basics.

Exceptions in Java

An unexpected event that disturbs the normal flow of the program is called an Exception. This can be due to various reasons such as dividing by zero, accessing an invalid index in an array, or trying to read a file that does not exist.
You can take an analogy with a car accident. In your commute to job you met an accident. This is an unexpected even that disturbs you normal flow of the day. How you are going to handle this situation (exception)? Similarly, for Java exceptions, you need to define explicitly how you are going to handle the exception in order to prevent the program from crashing.

As Java is an Object-Oriented Programming language, exceptions that occur in the program are represented as objects. This exception object describes an exceptional condition, e.g: divide by zero, that occurred. As a developer we will care about the Exceptions which are instances of the java.lang.Exception class or its subclasses. The figure below shows the hierarchy of exceptions in Java.

/posts/checked-vs-unchecked/images/Exception-Hierarchy.png
fig: Java Exception Hierarchy

How exception is handled in Java?

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    public static int divide(int a, int b) {
        return a / b;
    }
}

In order to handle exceptions in Java, we use the try-catch block. The code that might throw an exception is placed inside the try block, and the code to handle the exception is placed inside the catch block. In the example above, if we try to divide by zero, an ArithmeticException will be thrown, and the catch block will handle it gracefully by printing an error message without abnormal termination.

If Java were not to have this exception handling mechanism, exceptions and error must be checked and handled manually, through the use of error codes. This would make the code more complex and less readable. Instead, Java provides a robust exception handling mechanism that allows developers to handle exceptions gracefully.

Throwable is a class
The root class of the exception hierarchy is java.lang.Throwable. It might sound like a Interface, but it is actually a class. It has two main subclasses: java.lang.Exception and java.lang.Error.
Exception vs. Error
As a developer, we will only care about java.lang.Exception and its subclasses. The java.lang.Error class is used by the Java Virtual Machine (JVM) to indicate a system problem that is not intended to be caught by the application code. Examples include OutOfMemoryError and StackOverflowError.

Checked vs. Unchecked Exceptions

Checked Exceptions

Checked exceptions are exceptions that the compiler requires to be handled explicitly before the program can be compiled. They are enforced on the developer to help prevent common errors that may occur at runtime. This ensures smooth execution of the program by making the developer aware of potential exceptions early on. Examples of checked exceptions include IOException, SQLException, and ClassNotFoundException. These exceptions must be either caught using a try-catch block or declared in the method signature using the throws keyword. Idea behind this can be explained as follows: Missing file is a common issue and fundamental to file handling, thus Java forces you to handle it explicitly.

Analogy: You would always check if you have your movie tickets before going to the cinema—this is like a checked exception. However, you wouldn’t plan for something unexpected like getting into an accident on the way, which represents an unchecked exception.

public class CheckedExceptionExample {
    public static void main(String[] args) {
        try {
            readFile("nonexistent.txt");
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    } 
    public static void readFile(String fileName) throws IOException {
        FileReader fileReader = new FileReader(fileName);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line = bufferedReader.readLine();
        System.out.println(line);
        bufferedReader.close();
    }
}

If you try to compile the above code without handling the IOException, you will get a compilation error.

How to make your custom exception checked?

To make an exception checked, you need to extend the java.lang.Exception class. That’s all.

public class MyCheckedException extends Exception {
    public MyCheckedException(String message) {
        super(message);
    }
}

Unchecked Exceptions

The exceptions which are not checked by the compiler whether the programmer is handling or not. Such a type of exceptions is called unchecked exceptions.
E.g.: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, ShortCircuitAccidentException etc.

Whether it is checked or unchecked, every exception occurs at runtime only. There is no change of occurring any exception at compile time.

You probably wouldn’t carry an expensive medical kit to handle the possibility of a car accident—that’s an unchecked exception. It’s not something you would check for before going to the cinema.

// This compile fine as ArrayIndexOutOfBoundsException is an unchecked exception
public class UncheckedExceptionExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        System.out.println(numbers[5]); // This will throw ArrayIndexOutOfBoundsException
    }
}

How to make your custom exception unchecked?

To make an exception unchecked, you need to extend the java.lang.RuntimeException class.

public class MyUncheckedException extends RuntimeException {
    public MyUncheckedException(String message) {
        super(message);
    }
}

Fully Checked vs. Partially Checked Exceptions

A Checked exception is said to be fully checked if and only if all its child classes are also checked. E.g.: IOException, InterruptedException, etc.

A Checked exception is said to be partially checked if and only if some of its child classes are unchecked. E.g.: Exception, Throwable, etc.

The only possible partially checked exception in Java are Exception and Throwable. All other checked exceptions are fully checked.

Summary

In summary, Checked Exceptions extends Exception class and Unchecked Exceptions extends RuntimeException class. The main difference is that checked exceptions are checked at compile-time, while unchecked exceptions are checked at runtime.