Checked vs Unchecked Exceptions in Java

This article describes the differences between checked and unchecked exceptions in java.

3/24/20243 min read

In Java, exceptions are used to handle unexpected situations that can occur during the execution of a program. Java exceptions are divided into two main categories: checked exceptions and unchecked exceptions. Understanding the differences between these two types of exceptions is crucial for writing robust and reliable Java programs.

Introduction to Exceptions in Java

Exceptions in Java represent exceptional conditions that occur during the execution of a program, such as errors, failures, or unexpected situations. When an exception occurs, it disrupts the normal flow of the program and transfers control to an appropriate exception handler.

Java provides a comprehensive exception handling mechanism to manage exceptions effectively. This mechanism includes the `try`, `catch`, `finally`, and `throw` keywords, along with various exception classes defined in the `java.lang` package.

Checked Exceptions

Checked exceptions, also known as compiletime exceptions, are exceptions that must be explicitly declared in a method's signature using the `throws` keyword or handled using a `trycatch` block. These exceptions are checked by the compiler at compile time to ensure that they are properly handled by the calling code.

Characteristics of Checked Exceptions:

Must Be Declared or Handled: Checked exceptions must either be declared in the method signature using the `throws` clause or handled within a `trycatch` block.

Subclass of Exception: Checked exceptions are subclasses of the `java.lang.Exception` class or one of its subclasses, excluding `RuntimeException` and its subclasses.

CompileTime Checking: The compiler enforces handling or declaration of checked exceptions during compiletime, ensuring that the calling code acknowledges and handles potential exceptions.

Example of Checked Exceptions:

import java.io.FileReader;

import java.io.IOException;

public class FileReaderExample {

public static void main(String[] args) {

try {

FileReader fileReader = new FileReader("example.txt");

// Read file contents

} catch (IOException e) {

// Handle IOException

e.printStackTrace();

}

}

}

```

In this example, `FileReader` throws a checked exception `IOException`, which must be handled using a `trycatch` block to prevent compilation errors.

Unchecked Exceptions

Unchecked exceptions, also known as runtime exceptions, are exceptions that occur during the execution of a program and are not checked by the compiler. Unlike checked exceptions, unchecked exceptions do not require explicit handling or declaration, although handling them is still recommended for robust error recovery.

Characteristics of Unchecked Exceptions:

Do Not Need to Be Declared or Handled: Unchecked exceptions do not need to be declared in the method signature or handled using a `trycatch` block.

Subclass of RuntimeException: Unchecked exceptions are subclasses of the `java.lang.RuntimeException` class or one of its subclasses.

Not Checked by Compiler: The compiler does not enforce handling or declaration of unchecked exceptions during compiletime, allowing them to propagate up the call stack until caught by an appropriate handler.

Example of Unchecked Exceptions:

```java

public class DivideByZeroExample {

public static void main(String[] args) {

int dividend = 0;

int divisor = 0;

int result = dividend / divisor; // ArithmeticException: / by zero

System.out.println("Result: " + result);

}

}

In this example, dividing by zero results in an `ArithmeticException`, an unchecked exception. Since this exception is not checked by the compiler, the program compiles successfully, but it will throw an exception at runtime.

Key Differences Between Checked and Unchecked Exceptions

Handling Requirements

Checked Exceptions: Must be either declared in the method signature or handled using a `trycatch` block.

Unchecked Exceptions: Do not require explicit declaration or handling, although handling them is still recommended.

Compiler Enforcement

Checked Exceptions: Checked by the compiler during compile time to ensure proper handling or declaration.

Unchecked Exceptions: Not checked by the compiler, allowing them to propagate up the call stack until caught by an appropriate handler.

Subclass Hierarchy

Checked Exceptions: Subclasses of the `java.lang.Exception` class or one of its subclasses, excluding `RuntimeException` and its subclasses.

Unchecked Exceptions: Subclasses of the `java.lang.RuntimeException` class or one of its subclasses.

Usability

Checked Exceptions: Suitable for recoverable errors or situations where failure is expected and can be handled gracefully.

Unchecked Exceptions: Typically used for programming errors, such as logical errors or violations of programming contracts, where recovery may not be feasible.

Best Practices

Use Checked Exceptions for Recoverable Errors: Checked exceptions are suitable for recoverable errors where graceful error recovery or alternative actions can be taken.

Use Unchecked Exceptions for Programming Errors: Unchecked exceptions are more appropriate for programming errors, such as logic errors or invalid method arguments, where recovery may not be possible.

Handle Exceptions Appropriately: Regardless of whether an exception is checked or unchecked, always handle exceptions appropriately to ensure robust error recovery and prevent unexpected program termination.

Document Exception Handling: Document the expected exceptions thrown by methods to provide clarity to callers and aid in error handling.

Conclusion

In Java, exceptions play a crucial role in handling errors and exceptional conditions during program execution. Checked exceptions and unchecked exceptions represent two distinct categories of exceptions, each with its own characteristics, handling requirements, and best practices. Understanding the differences between these types of exceptions is essential for writing robust, reliable, and maintainable Java programs.

While checked exceptions are checked by the compiler and must be either declared or handled explicitly, unchecked exceptions are not checked by the compiler and do not require explicit handling. Both types of exceptions serve different purposes and should be used appropriately based on the nature of the error or exceptional condition being handled.

By following best practices and effectively using checked and unchecked exceptions, Java developers can enhance the reliability, robustness, and maintainability of their codebases, leading to improved software quality and user satisfaction.

Spring Cloud Gateway