Types of Exceptions

Thinking

Exceptions in Java come in different forms, each representing various kinds of errors or unusual conditions. Knowing the types helps you decide how to handle them effectively and write robust code.

Understanding checked, unchecked, and error exceptions is key to mastering Java’s exception handling model.

Description

Java exceptions are broadly categorized into three main types based on when and how they are handled:

  • Checked Exceptions: These exceptions are checked at compile-time. The programmer is forced to handle them using try-catch or declare them with throws.
    Example: IOException, SQLException
  • Unchecked Exceptions: Also called runtime exceptions, these occur during program execution and do not need explicit handling.
    Example: NullPointerException, ArithmeticException
  • Errors: Serious problems typically external to the application (e.g., JVM errors). These are not meant to be caught by programs.
    Example: OutOfMemoryError, StackOverflowError

Note: Handling checked exceptions improves program reliability, while unchecked exceptions are often caused by programmer errors.

Video Resources

Examples (code)

Checked Exception Example (File Handling)


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class CheckedExceptionDemo {
    public static void main(String[] args) {
        try {
            File file = new File("nonexistent.txt");
            Scanner sc = new Scanner(file);
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        }
    }
}
  

Unchecked Exception Example (Null Pointer)


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

Error Example (Stack Overflow)


public class ErrorDemo {
    public static void recursive() {
        recursive(); // Causes StackOverflowError
    }

    public static void main(String[] args) {
        recursive();
    }
}
  

Real-World Applications

File I/O Operations

Checked exceptions help manage missing or inaccessible files gracefully.

Bug Detection

Unchecked exceptions often point to programming errors that need fixing.

System Stability

Errors indicate critical JVM issues that cannot be handled in typical programs.

Interview Questions

Q1: What is a checked exception?

Show Answer

Exceptions that are checked at compile time and must be handled or declared.

Q2: Give examples of unchecked exceptions.

Show Answer

Examples include NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.

Q3: Can errors be caught in Java?

Show Answer

Technically yes, but errors represent serious problems and should not be caught in normal application code.