DEV Community

realNameHidden
realNameHidden

Posted on

⚠️ What’s the Difference Between Checked Exception and Unchecked Exception in Java?

Learn the difference between checked and unchecked exceptions in Java with simple explanations, examples, and best practices for writing reliable Java programs.


Introduction

Imagine you’re on a road trip. You’ve checked your fuel, brakes, and route — everything looks good. But halfway through, your tire bursts!

In Java programming, something similar happens when errors or unexpected events interrupt the normal flow of a program. These are called exceptions. Some issues can be predicted and handled in advance (like checking your fuel before the trip) — others happen suddenly (like a flat tire).

That’s why Java divides exceptions into Checked and Unchecked Exceptions.

Understanding this difference helps you write robust, error-free code that gracefully handles problems instead of crashing unexpectedly. Let’s explore this concept in a simple, practical way.


Core Concepts: Checked vs Unchecked Exceptions

When a program encounters an error, Java throws an exception.
Exceptions are objects that describe what went wrong and where.

Java classifies exceptions into two main categories based on when they’re checked — during compile-time or runtime.


✅ Checked Exceptions — Caught at Compile-Time

Definition:
Checked exceptions are the ones that the compiler forces you to handle — either by using try-catch or by declaring them with throws.

Think of them as expected problems that you can plan for.

Examples:

  • IOException – when reading a file that might not exist
  • SQLException – when interacting with a database
  • FileNotFoundException – when a file path is incorrect

If you don’t handle a checked exception, your program won’t compile.

Analogy:
Like a cautious driver checking the route and car condition before a journey — Java wants you to handle these issues before the code even runs.


⚡ Unchecked Exceptions — Detected at Runtime

Definition:
Unchecked exceptions are not checked at compile-time. They occur while the program is running, often due to programming mistakes.

Examples:

  • NullPointerException – when you try to access an object that’s null
  • ArrayIndexOutOfBoundsException – when accessing invalid array index
  • ArithmeticException – dividing by zero

These are subclasses of RuntimeException.

Analogy:
Imagine texting while driving — the car suddenly swerves off the road. The problem wasn’t predictable by the system, but it happens due to poor coding habits or logic errors.


🧠 Key Difference at a Glance

Feature Checked Exception Unchecked Exception
Checked by Compiler Yes No
Occurs at Compile-time Runtime
Handling Required? Must be handled or declared Optional
Examples IOException, SQLException NullPointerException, ArithmeticException
Subclass of Exception RuntimeException

Code Examples

Example 1: Handling a Checked Exception

// Java 21 Example - Checked Exception Demo
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class CheckedExceptionExample {
    public static void main(String[] args) {
        try {
            // Trying to open a file that might not exist
            BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
            String line = reader.readLine();
            System.out.println("File content: " + line);
            reader.close();
        } catch (IOException e) {
            // Handling checked exception
            System.out.println("Oops! File not found or cannot be read: " + e.getMessage());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

🧩 Explanation:

  • FileReader and BufferedReader throw a checked exception (IOException) if the file isn’t found.
  • You must handle it using a try-catch block, or the compiler will throw an error.
  • This ensures that your program won’t crash if the file is missing.

Example 2: Demonstrating an Unchecked Exception

// Java 21 Example - Unchecked Exception Demo
public class UncheckedExceptionExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30};
        try {
            System.out.println("Accessing element: " + numbers[5]); // Invalid index
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: You tried to access an invalid index!");
        }

        String text = null;
        try {
            System.out.println(text.length()); // NullPointerException
        } catch (NullPointerException e) {
            System.out.println("Error: Tried to use a null object!");
        }

        System.out.println("Program continues smoothly...");
    }
}
Enter fullscreen mode Exit fullscreen mode

🧩 Explanation:

  • Accessing index 5 in an array of size 3 throws an unchecked ArrayIndexOutOfBoundsException.
  • Calling text.length() on a null reference triggers a NullPointerException.
  • These are runtime issues — the compiler won’t warn you, but they’ll crash the program if unhandled.

Best Practices for Handling Exceptions in Java

  1. Handle Checked Exceptions Gracefully
    Use try-catch or throws to manage known risks like file operations or network calls. Don’t ignore them!

  2. Avoid Overusing try-catch Blocks
    Too many nested try-catch blocks make your code hard to read. Centralize exception handling when possible.

  3. Never Suppress Exceptions Silently
    Always log meaningful error messages. Empty catch blocks make debugging painful later.

  4. Use Custom Exceptions for Business Logic
    Create your own exceptions (e.g., InvalidUserInputException) to make code clearer and more descriptive.

  5. Don’t Overhandle Unchecked Exceptions
    Focus on fixing the logic rather than just catching every RuntimeException.


Conclusion

In Java programming, checked exceptions prepare you for known issues at compile-time, while unchecked exceptions handle unexpected runtime errors.

Understanding their difference helps you decide when to anticipate errors and when to fix logic flaws. It’s a crucial skill for writing clean, maintainable, and user-friendly Java applications.

So next time you see a try-catch block or a NullPointerException, you’ll know exactly what’s happening behind the scenes — and how to handle it like a pro.


Top comments (0)