Exception Handling in Java — Java Technical Interview Questions & Answers

Exception Handling in Java

Exception Handling in Java

  • Exceptions are problems at runtime. Handling them keeps the app from crashing blindly. try holds risky code (divide, file, parse). catch runs backup code if that problem happens. finally runs cleanup whether error happened or not — close files, close connections.
  • Two families: checked (must handle or declare) and unchecked (RuntimeException family). Catch specific exceptions and give a clear message. Empty catch blocks hide bugs.
  • Explain try / catch / finally, then checked vs unchecked in one line each.
  • Let's take this on the board with one tiny Main class — no extra files. Exception Handling in Java — output: Cannot divide by zero. 10/0 throws ArithmeticException; catch prints the message. x is never printed. Start from main, go line by line, and stop at each print. That output is the proof for Exception Handling.
  try { risky }
        │ throws
        ▼
  catch → message
        │
        ▼
  finally → cleanup

Technical Interview Tip: try/catch/finally + checked vs unchecked.

Code Examples for Exception Handling in Java

Example

// try-catch demo
public class Main {
  public static void main(String[] args) {
    try {
      int x = 10 / 0;
      System.out.println(x);
    } catch (ArithmeticException e) {
      System.out.println("Cannot divide by zero");
    }
  }
}

Exception Handling in Java — output: Cannot divide by zero. 10/0 throws ArithmeticException; catch prints the message. x is never printed.

How to Explain Exception Handling in Java to an Interviewer

What goes in try?

Risky code

What does finally do?

Cleanup Runs whether error happened or not

Checked vs unchecked?

Checked must handle or declare Unchecked = RuntimeException family