Checked and unchecked exceptions are two categories of exceptions in Java. The main difference is that checked exceptions are verified by the compiler at compile time, whereas unchecked exceptions are identified during program execution.
Key Points: • Checked exceptions must be either handled using a try-catch block or declared using the throws keyword. • Unchecked exceptions do not require explicit handling or declaration. • Checked exceptions are subclasses of Exception (excluding RuntimeException). • Unchecked exceptions are subclasses of RuntimeException. • Checked exceptions usually represent recoverable conditions, while unchecked exceptions often indicate programming errors.
Example: • Checked Exception: IOException, SQLException, ClassNotFoundException • Unchecked Exception: NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException
Code Example:
// Checked Exception
public void readFile() throws IOException {
FileReader file = new FileReader("data.txt");
}
// Unchecked Exceptionint result = 10 / 0; // ArithmeticException
Interview Tip: A concise interview answer is:
"Checked exceptions are validated at compile time and must be handled or declared using throws. Unchecked exceptions occur at runtime and do not require explicit handling. Checked exceptions are subclasses of Exception, while unchecked exceptions are subclasses of RuntimeException."
Quick Comparison:
Checked Exception: • Checked at compile time • Must be handled or declared • Example: IOException
Unchecked Exception: • Occurs at runtime • Handling is optional • Example: NullPointerException