Difference between Checked and Unchecked Exception in Java

In this article, we will have a detailed discussion on the differences between Checked and Unchecked Exception in Java. So. let’s get started.

Difference between Checked and Unchecked Exception in Java

What is Checked Exception in Java?

Checked exceptions in Java are exceptions that the compiler requires you to handle, either by catching them with a try-catch block or by declaring them in the method’s signature using the throws keyword. They are typically used for situations that can be anticipated and managed during program execution.

Code Example:

Let’s look into the below Java Code example for Checked Exception in Java.

public class CheckedExceptionExample {

    public static void main(String[] args) {
        try {
            // Trying to read a file that may not exist
            FileReader fileReader = new FileReader("nonexistent.txt");
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        }
    }
}

Output

File not found: nonexistent.txt (No such file or directory)

In the example, the FileReader constructor may throw a FileNotFoundException if the specified file doesn’t exist. Since this is a checked exception, we are required to catch it using a try-catch block to prevent compilation errors.

Read More : List of Checked Exception in Java

What is Unchecked Exception in Java?

Unchecked exceptions in Java are exceptions that the compiler doesn’t require you to handle explicitly. They usually result from programming errors or unexpected situations that might occur during runtime, such as null pointer dereferences or arithmetic exceptions.

Code Example:

Let’s look into the below Java Code example for Unchecked Exception in Java.

public class UncheckedExceptionExample {

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        
        // Attempting to access an out-of-bounds index
        int result = numbers[5];
        
        System.out.println("Result: " + result);
    }
}

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
    at UncheckedExceptionExample.main(UncheckedExceptionExample.java:8)

In the example, the code attempts to access an index that is out of bounds in the numbers array. This leads to an ArrayIndexOutOfBoundsException, an unchecked exception. Since unchecked exceptions don’t need to be caught explicitly, the program terminates with an error message indicating the exception’s details.

Read More : List of Unchecked Exception in Java

Difference between Checked and Unchecked Exception in Java

Let’s now look into the key differences between Checked and Unchecked Exception in Java.

AspectChecked ExceptionUnchecked Exception
Compilation RequirementMust be caught or declared using throws.Not required to be caught or declared.
ExamplesFileNotFoundException, IOExceptionNullPointerException, ArrayIndexOutOfBoundsException
Intended UseFor situations that can be anticipated and managed.For programming errors or unexpected situations.
Checked at CompilationYesNo
InheritanceExtends ExceptionExtends RuntimeException
HandlingRequires try-catch or throws declaration.Optional; can be caught but not mandatory.
Default BehaviorForces handling; improves code robustness.May terminate program if not caught.
Custom ExceptionsCan create custom checked exceptions.Can create custom unchecked exceptions.
Common CausesI/O operations, networking, file handling.Null references, array bounds, arithmetic errors.

Conclusion: Difference between Checked and Unchecked Exception in Java

In this comprehensive article, we delved into the difference between Checked and Unchecked Exception in Java. Checked exceptions necessitate handling through either try-catch blocks or throws declarations, making them suitable for situations that can be anticipated and managed.

On the other hand, Unchecked exceptions are not mandated to be caught explicitly and commonly arise from programming errors or unforeseen circumstances during runtime. The provided code examples illustrated the practical application of both types of exceptions.

By grasping the nuances between Checked and Unchecked Exceptions, Java developers can make informed decisions about exception handling strategies.

Java Exceptions Must-Read Articles:

Leave a Reply

Your email address will not be published. Required fields are marked *