Java Throw Exception — Java Technical Interview Questions & Answers

Java Throw Exception

Java Throw Exception

  • throw actually throws an exception object: throw new IllegalArgumentException("age < 0");. Use it when your method detects a bad situation.
  • You throw one object. After throw, the next lines in that block do not run. A checked exception must be caught or declared with throws.
  • Don’t throw null. Don’t throw for normal flow (like “user clicked cancel”). Exceptions are for problems.
  • Let's take this on the board with one tiny Main class — no extra files. Java Throw Exception — 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 Throw Exception.
  try { risky }
        │ throws
        ▼
  catch → message
        │
        ▼
  finally → cleanup

Technical Interview Tip: Write throw new IllegalArgumentException("bad age") and say it stops the method.

Code Examples for Java Throw Exception

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");
    }
  }
}

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

How to Explain Java Throw Exception to an Interviewer

What does throw do?

Throws an exception object now

How many objects can throw throw at once?

One