Java.Core.What is the difference between checked and unchecked exceptions?

Difference Between Checked and Unchecked Exceptions in Java

Exceptions in Java are categorized into checked and unchecked exceptions based on whether the compiler enforces handling.


1. Checked Exceptions (Compile-Time Exceptions)

Definition:
Checked exceptions are exceptions that the compiler forces you to handle using:

  • A try-catch block OR
  • A throws clause in the method signature.

When Do They Occur?
They occur in situations beyond the programmer’s control (e.g., file handling, database connections, network issues).

Key Features:

  • The compiler enforces handling at compile-time.
  • They must be handled or declared in the method signature.
  • Extends Exception (but NOT RuntimeException).

Examples of Checked Exceptions:

ExceptionWhen It Occurs
IOExceptionFile read/write operation fails
SQLExceptionDatabase access error
FileNotFoundExceptionThe specified file does not exist
InterruptedExceptionA thread is interrupted
ClassNotFoundExceptionA required class is not found at runtime

Example: Handling a Checked Exception Using try-catch

import java.io.*;

public class CheckedExceptionExample {
    public static void main(String[] args) {
        try {
            FileReader file = new FileReader("test.txt"); // May throw FileNotFoundException
            BufferedReader br = new BufferedReader(file);
            System.out.println(br.readLine());
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
        }
    }
}

Example: Declaring a Checked Exception with throws

import java.io.*;

public class CheckedExample {
    public static void readFile() throws IOException {
        FileReader file = new FileReader("test.txt"); // Must handle or declare
        BufferedReader br = new BufferedReader(file);
        System.out.println(br.readLine());
    }

    public static void main(String[] args) {
        try {
            readFile();
        } catch (IOException e) {
            System.out.println("Handled: " + e.getMessage());
        }
    }
}

2. Unchecked Exceptions (Runtime Exceptions)

🚀 Definition:
Unchecked exceptions occur due to programming mistakes and are not forced to be handled by the compiler.

🚀 When Do They Occur?
Unchecked exceptions result from logic errors (e.g., dividing by zero, accessing null references, using invalid array indexes).

🚀 Key Features:

  • The compiler does not enforce handling.
  • They should be prevented by writing better code instead of using try-catch.
  • Extends RuntimeException.

🚀 Examples of Unchecked Exceptions (RuntimeException and its subclasses):

ExceptionWhen It Occurs
NullPointerExceptionAccessing a null object
ArrayIndexOutOfBoundsExceptionAccessing an invalid array index
ArithmeticExceptionDivision by zero
IllegalArgumentExceptionPassing invalid method arguments
ClassCastExceptionIncorrect type conversion

🚀 Example: Unchecked Exception (NullPointerException)

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

🛠 Better Approach: Always check for null values before accessing an object.

if (str != null) {
    System.out.println(str.length());
} else {
    System.out.println("String is null!");
}

🚀 Example: Unchecked Exception (ArrayIndexOutOfBoundsException)

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

🛠 Better Approach: Always check the array length before accessing an index.

if (5 < numbers.length) {
    System.out.println(numbers[5]);
} else {
    System.out.println("Index out of bounds!");
}

3. Differences Between Checked and Unchecked Exceptions

FeatureChecked ExceptionUnchecked Exception
Inherits fromException (but NOT RuntimeException)RuntimeException
Compiler Forces Handling?✅ Yes (try-catch or throws required)❌ No (can be ignored)
Caused by?External factors (files, DB, network)Programming mistakes (null, bad index)
Should Be Handled?✅ Yes, because it is recoverable🚫 No, should be prevented with better code
ExamplesIOException, SQLException, FileNotFoundExceptionNullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException

4. When to Use Checked vs. Unchecked Exceptions?

Use Checked Exceptions if:

  • The problem is recoverable (like file or network failures).
  • You expect the caller to handle the exception properly.

Use Unchecked Exceptions if:

  • The issue is a coding mistake (like accessing a null reference).
  • The programmer should fix the bug instead of handling it at runtime.

5. Custom Exceptions

You can create your own exceptions by extending Exception (for checked) or RuntimeException (for unchecked).

Custom Checked Exception

class CustomCheckedException extends Exception {
    public CustomCheckedException(String message) {
        super(message);
    }
}

public class CustomExceptionExample {
    public static void validateAge(int age) throws CustomCheckedException {
        if (age < 18) {
            throw new CustomCheckedException("Age must be at least 18");
        }
    }

    public static void main(String[] args) {
        try {
            validateAge(16);
        } catch (CustomCheckedException e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}

Custom Unchecked Exception

class CustomUncheckedException extends RuntimeException {
    public CustomUncheckedException(String message) {
        super(message);
    }
}

public class CustomRuntimeExceptionExample {
    public static void validateNumber(int num) {
        if (num < 0) {
            throw new CustomUncheckedException("Number cannot be negative");
        }
    }

    public static void main(String[] args) {
        validateNumber(-5); // No try-catch needed, but will crash if not prevented
    }
}

Final Thoughts

Checked exceptions should be handled because they are expected failures (file I/O, network issues).
Unchecked exceptions should be avoided by writing better code (null checks, proper indexing).
Errors (like OutOfMemoryError) should never be caught—they indicate serious system failures.
Use throws for checked exceptions and try-catch for expected failures in your program.

This entry was posted in Без рубрики. Bookmark the permalink.