try-catch

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

TL;DR

  • The try block encloses code that might throw an exception.
  • The catch block contains the logic to handle the specific exception if it is thrown.
  • A try block must be followed by at least one catch block (or a finally block).

Concept

When code inside the try block throws an exception, the JVM stops executing the rest of the try block immediately. It then looks at the attached catch blocks in order from top to bottom, checking if the thrown exception’s type matches the type declared in the catch parameter.

If a match is found, the code inside the catch block executes. If no match is found, the exception is propagated up the call stack to the method that called it.

Examples

import java.util.Scanner;

public class TryCatchExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number to divide 100 by: ");
        
        try {
            // Risky code
            String input = scanner.nextLine();
            int number = Integer.parseInt(input); 
            
            int result = 100 / number;
            
            System.out.println("Result: " + result);
            
        } catch (NumberFormatException e) {
            // Executes if they type letters instead of a number
            System.out.println("Invalid input. Please type digits only.");
            
        } catch (ArithmeticException e) {
            // Executes if they type '0'
            System.out.println("Cannot divide by zero!");
            
        } catch (Exception e) {
            // Catch-all for any other unforeseen exception
            System.out.println("An unknown error occurred: " + e.getMessage());
        }
        
        System.out.println("Program execution continues normally.");
    }
}

Interview Questions

Q: Does the order of multiple catch blocks matter?
A: Yes, absolutely. catch blocks must be ordered from the most specific exception to the most general. If you put catch (Exception e) at the very top, it will catch every possible exception (because of polymorphism), rendering all subsequent catch blocks unreachable. The compiler will actually throw an “Unreachable code” error if you try to put a subclass catch block after a superclass catch block.

Q: What happens if an exception is thrown inside a catch block?
A: If a catch block throws an exception, it behaves exactly like an exception thrown from normal code. It will abruptly terminate the catch block and propagate up the call stack unless it is surrounded by a nested try-catch inside that specific catch block.