Exceptions

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • An Exception is an unwanted or unexpected event occurring during program execution that disrupts the normal flow of instructions.
  • Java uses an Object-Oriented approach to exception handling: when an error occurs, an Exception Object is created and thrown.
  • The root class of the exception hierarchy is java.lang.Throwable.

Concept

In traditional programming languages, error handling was often done by returning error codes (e.g., -1 if a file wasn’t found). This led to messy code where normal logic was intertwined with error-checking logic.

Java’s exception handling cleanly separates error-handling code from regular code. When a problem occurs (like dividing by zero, or a missing file), Java throws an Exception object containing information about the error (its type and the state of the program). The runtime system then searches backward through the call stack to find a block of code (a catch block) willing to catch and handle the exception.

The Hierarchy

  1. Throwable (Root)
  2. Error (Serious JVM problems, e.g., OutOfMemoryError)
  3. Exception (Programmatic errors)
  4. RuntimeException (A special subclass of Exception for unchecked errors)

Examples

public class ExceptionIntro {
    public static void main(String[] args) {
        
        System.out.println("Program started...");
        
        try {
            // This will throw an ArithmeticException
            int result = 10 / 0; 
            
            // This line will NEVER be reached
            System.out.println("Result is " + result); 
            
        } catch (ArithmeticException e) {
            // We caught the thrown exception object 'e'
            System.out.println("An error occurred: " + e.getMessage());
        }
        
        // The program continues normally because the exception was handled
        System.out.println("Program finished safely.");
    }
}

Interview Questions

Q: What happens if an exception is thrown but never caught?
A: If no catch block is found anywhere in the call stack, the exception reaches the Default Exception Handler provided by the JVM. The JVM will immediately terminate the program (or the specific thread) and print the exception’s name, description, and stack trace to the standard error stream.

Q: Can you create an object of java.lang.Throwable?
A: Yes, Throwable is a concrete class (not abstract or an interface), so you can instantiate it. However, it is extremely bad practice. You should only throw objects that subclass Exception or Error.