Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Checked vs Unchecked Exceptions in Java

Introduction

In Java, exceptions are events that disrupt the normal flow of a program's execution. They can be classified into two categories: checked exceptions and unchecked exceptions. Understanding these categories is crucial for effective exception handling in Java applications.

Checked Exceptions

Definition

Checked exceptions are exceptions that are checked at compile-time. The Java compiler requires that these exceptions be either handled using a try-catch block or declared in the method signature using the throws keyword.

Common Checked Exceptions

  • IOException
  • SQLException
  • ClassNotFoundException

Example


import java.io.FileReader;
import java.io.IOException;

public class CheckedExceptionExample {
    public static void main(String[] args) {
        try {
            FileReader file = new FileReader("nonexistentfile.txt");
        } catch (IOException e) {
            System.out.println("File not found: " + e.getMessage());
        }
    }
}
                

Unchecked Exceptions

Definition

Unchecked exceptions are exceptions that are not checked at compile-time. They are subclasses of RuntimeException and can occur during the runtime of the program. The compiler does not require these exceptions to be handled or declared.

Common Unchecked Exceptions

  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • IllegalArgumentException

Example


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

Best Practices

Key Takeaways

  • Always handle checked exceptions to prevent application crashes.
  • Use custom exceptions to provide more meaningful error messages.
  • Avoid catching generic Exception or Throwable unless necessary.
  • Document the exceptions that your methods can throw.
  • Use try-with-resources for automatic resource management.

FAQ

What happens if a checked exception is not handled?

If a checked exception is not handled, the program will fail to compile.

Can we catch unchecked exceptions?

Yes, although it's optional. Catching them can help prevent crashes but can also obscure bugs.

How do I create a custom checked exception?

To create a custom checked exception, extend the Exception class.