What is the exception and the differences between checked and unchecked exceptions?

An exception is an event that occurs during program execution and interrupts the normal flow of the application. Java provides an exception-handling mechanism to detect, handle, and recover from such situations, making applications more reliable and robust.

Key Points: • Exceptions are represented as objects and are part of Java's exception hierarchy. • Checked exceptions are verified by the compiler and must be either handled using try-catch or declared using throws. • Unchecked exceptions occur at runtime and are not required to be handled explicitly. • Checked exceptions usually represent recoverable conditions, while unchecked exceptions often indicate programming errors. • Proper exception handling improves application stability and error management.

Differences Between Checked and Unchecked Exceptions:

Checked Exceptions: • Checked at compile time • Must be handled or declared • Subclasses of Exception (excluding RuntimeException) • Examples: IOException, SQLException, ClassNotFoundException

Unchecked Exceptions: • Checked at runtime • Handling is optional • Subclasses of RuntimeException • Examples: NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException

Example: If a file is missing while reading data, Java throws a checked exception such as FileNotFoundException because the application may be able to recover. On the other hand, accessing a null object reference causes a NullPointerException, which is an unchecked exception and typically indicates a coding mistake.

Code Example:

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

public class Demo {

    public static void main(String[] args) {

        try {
            FileReader file = new FileReader("data.txt");
        } catch (IOException e) {
            System.out.println("Checked Exception Handled");
        }

        String str = null;
        // str.length(); // Throws NullPointerException (Unchecked Exception)
    }
}

Interview Tip: A concise interview answer is:

"An exception is an abnormal event that disrupts the normal execution of a program. Checked exceptions are validated by the compiler and must be handled or declared, whereas unchecked exceptions occur at runtime and do not require mandatory handling. Checked exceptions typically represent recoverable situations, while unchecked exceptions usually indicate programming errors."