Home » Java Tutorial » Java Exception Handling: Checked and Unchecked Exception

Java Exception Handling: Checked and Unchecked Exception

In Java, Exception Handling is a powerful mechanism to handle runtime errors, allowing your application to continue its normal flow even when something goes wrong.

Whether you’re a beginner or preparing for interviews, understanding how to handle exceptions using try, catch, throw, throws, and finally is essential.

What is an Exception in Java?

An Exception in Java is an unexpected event that occurs during the execution of a program and disrupts its normal flow.

For example:

int result = 10 / 0; // ArithmeticException

This will cause your program to crash unless you handle it properly using exception handling.

Let’s break it down:

1. “Unexpected event”:

This means something goes wrong while your program is running.

  • Maybe a file doesn’t exist
  • A number is divided by zero
  • A user input is invalid
  • You try to access something that’s not there (like an array element at a wrong index)

Java throws an exception to notify you that something went wrong.

2. “During execution (runtime)”:

Exceptions usually happen after the program compiles successfully, but during execution.

This makes exceptions different from compile-time errors, which are syntax mistakes like missing semicolons or brackets.

3. “Disrupts the normal flow”:

When an exception occurs and is not handled, Java stops running your program and throws an error message called a stack trace.

This means your program won’t continue to the next line unless you handle that exception.

Types of Exceptions in Java

1. Checked Exceptions (Compile-time Exception)

2. Unchecked Exceptions (Run-time Exception)

1. Checked Exceptions

Checked exceptions are the exceptions that are checked at compile-time. This means that if your code might throw a checked exception, you must handle it using a try-catch block or declare it using the throws keyword. If you don’t, the program won’t compile.

These exceptions usually occur due to external factors (like file I/O, database connections, etc.) that are outside the control of the program.

Real-Life Analogy

Imagine you’re planning a train journey. You book your ticket online. Now, many things could go wrong:

  • The website could be down.
  • The server could be busy.
  • The internet could disconnect.

These problems might happen, and so the app shows you proper error messages and handles them. You don’t crash the app — you handle the problem and maybe retry or show a helpful message.

Java’s checked exceptions work the same way:
They force the programmer to anticipate problems that can happen due to external resources like files, databases, or networks — and handle them properly.

Why Are They Called “Checked”?

Because the Java compiler checks for them.

If you write code that might throw a checked exception, and you don’t handle it, you will get a compile-time error.

Common Checked Exceptions

ExceptionWhat It Means
IOExceptionError during input/output (like file read/write)
FileNotFoundExceptionFile not found on your computer
SQLExceptionError while accessing the database
ClassNotFoundExceptionClass you’re trying to load does not exist

Example 1: File Not Found

Let’s say you’re trying to read a file named data.txt.

import java.io.FileReader;
import java.io.FileNotFoundException;

public class CheckedExample1 {
    public static void main(String[] args) {
        try {
            FileReader file = new FileReader("data.txt");
            System.out.println("File opened successfully");
        } catch (FileNotFoundException e) {
            System.out.println("File not found! Please check the file path.");
        }
    }
}

Output:

File not found! Please check the file path.

Explanation:

  • FileReader throws a FileNotFoundException (a checked exception).
  • We must handle it using try-catch.
  • If the file doesn’t exist, the program won’t crash — it shows a message instead.

Example 2: Declaring with throws

If you don’t want to handle the exception where it occurs, you can declare it using throws.

import java.io.FileReader;
import java.io.FileNotFoundException;

public class CheckedExample2 {
    public static void readFile() throws FileNotFoundException {
        FileReader file = new FileReader("data.txt");
        System.out.println("Reading file...");
    }

    public static void main(String[] args) {
        try {
            readFile();
        } catch (FileNotFoundException e) {
            System.out.println("Handled in main: File not found.");
        }
    }
}

Explanation:

  • The readFile() method says: “Hey, I might throw a FileNotFoundException, handle it where you call me.”
  • We handle it in the main() method.

Use Case Scenarios

Checked exceptions are used when the error is not due to the programmer’s fault, but due to external reasons, like:

ScenarioException
Reading a file that might not existFileNotFoundException
Writing to a disk that might be fullIOException
Connecting to a databaseSQLException
Loading a class at runtimeClassNotFoundException

What Happens If You Don’t Handle It?

Let’s remove the try-catch and see what happens:

FileReader file = new FileReader("data.txt"); // compile-time error

🛑 You’ll get:

Unhandled exception: java.io.FileNotFoundException

✔ Java will not let you compile the code until you handle or declare the exception.

Summary: Key Points About Checked Exceptions

FeatureDescription
Checked by Compiler?✅ Yes
When do they occur?Mostly during external operations (I/O, DB, etc.)
Must be handled or declared?✅ Yes
Common examplesIOException, SQLException, FileNotFoundException
Program crash if not handled?🚫 It won’t compile in the first place

2. Unchecked Exceptions

Unchecked Exceptions are runtime exceptions in Java that are not checked at compile time.
This means the Java compiler does not force you to handle them using try-catch or declare them with throws.

They occur when there’s a bug or logic error in your program, and often cause the program to crash if not handled.

Why are they called “Unchecked”?

Because the compiler does not check whether you’ve handled them.
You can handle them — but you’re not forced to. These exceptions happen due to programming mistakes like:

  • Dividing by zero
  • Accessing null objects
  • Using invalid array indexes

Where Do Unchecked Exceptions Come From?

All unchecked exceptions in Java inherit from the class:

java.lang.RuntimeException

And RuntimeException extends the base class Exception, but it’s not a checked exception.

Common Unchecked Exceptions (with Examples)

1. ArithmeticException

ArithmeticException occurs when an illegal mathematical operation is performed — most commonly when you divide by zero.

Real-life Analogy:

You’re trying to divide 10 apples among 0 people. You can’t — it’s mathematically undefined.

public class Example1 {
    public static void main(String[] args) {
        int result = 10 / 0;  // ArithmeticException
        System.out.println("Result: " + result);
    }
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Example1.main(Example1.java:3)

Explanation:

  • Java doesn’t allow division by 0 for integers.
  • So when 10 / 0 is executed, Java throws an ArithmeticException.
  • Since the exception is not handled, the program crashes before it reaches System.out.println("Result...").

Fix / Safe Handling:

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

Output:

Error: Cannot divide by zero.

2. ❌ NullPointerException

This happens when you try to access or call a method/field on a null object (i.e., an object that hasn’t been initialized).

Real-life Analogy:

You try to use a phone without inserting the battery. The phone is not active, so pressing buttons won’t work.

public class Example2 {
    public static void main(String[] args) {
        String name = null;
        System.out.println(name.length()); // NullPointerException
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException
    at Example2.main(Example2.java:4)

Explanation:

  • name is declared as null, meaning it does not point to any memory address (no object is created).
  • Trying to access name.length() means you’re calling a method on something that doesn’t exist — this leads to a NullPointerException.

Fix / Safe Handling:

public class Example2Safe {
    public static void main(String[] args) {
        String name = null;
        if (name != null) {
            System.out.println("Length: " + name.length());
        } else {
            System.out.println("Error: name is null.");
        }
    }
}

Output:

Error: name is null.

3. ArrayIndexOutOfBoundsException

This happens when you try to access an array index that doesn’t exist — either negative or greater than or equal to array length.

Real-life Analogy:

You try to pick the 6th item from a box that only has 3 items — there’s nothing there.

public class Example3 {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30};
        System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException
    }
}

Output:

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

Explanation:

  • The array numbers has 3 elements → indices 0, 1, and 2.
  • Trying to access numbers[5] is invalid because index 5 does not exist.
  • Java throws an ArrayIndexOutOfBoundsException.

Fix / Safe Handling:

public class Example3Safe {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30};
        int index = 5;
        if (index >= 0 && index < numbers.length) {
            System.out.println("Value: " + numbers[index]);
        } else {
            System.out.println("Error: Invalid array index.");
        }
    }
}

Output:

Error: Invalid array index.

Summary of the above Three Exceptions

Exception TypeCauseExampleReal-Life Analogy
ArithmeticExceptionDivision by zeroint a = 10 / 0;Divide 10 apples among 0 people
NullPointerExceptionUsing a null objectname.length(); when name = nullUsing a phone with no battery
ArrayIndexOutOfBoundsExceptionAccessing invalid array indexarray[5] when array has only 3 elementsTaking 6th item from a 3-item list

Some More Unchecked Exceptions

Exception TypeCauseReal-Life Analogy
ClassCastExceptionInvalid object type castFitting square peg in round hole
NumberFormatExceptionInvalid number formatConverting “abc” to number
IllegalArgumentExceptionWrong argumentsSetting invalid thread priority
IllegalStateExceptionObject not in right stateReading a closed file

❓ Why Do Unchecked Exceptions Exist?

Unchecked exceptions are:

  • Logic errors made by the programmer
  • Not usually recoverable
  • Should be fixed in the code, not caught and hidden

Java doesn’t force you to handle them because:

  • They are usually due to bugs
  • Catching them might hide errors instead of solving them