Custom Exception in Java — Java Technical Interview Questions & Answers

Custom Exception in Java

Custom Exception in Java

  • A custom exception is your own error type: class AgeException extends Exception { ... }. Use it when a business rule fails (age < 0, balance too low) and you want a clear name.
  • Extend Exception for checked (caller must handle). Extend RuntimeException for unchecked. Give a constructor that takes a message: super(msg).
  • Don’t invent a custom exception for every tiny check. Use it when the name helps the caller.
  • Let's take this on the board with one tiny Main class — no extra files. Output: Asha scored 72 then Pass. Real Main. Swap marks/name to show one idea from Custom Exception in Java. Start from main, go line by line, and stop at each print. That output is the proof for Custom Exception.
  try { risky }
        │ throws
        ▼
  catch → message
        │
        ▼
  finally → cleanup

Technical Interview Tip: Write class AgeException extends Exception { AgeException(String m) { super(m); } } then throw it.

Code Examples for Custom Exception in Java

Example

// Custom
public class Main {
  public static void main(String[] args) {
    int marks = 72;
    String name = "Asha";
    System.out.println(name + " scored " + marks);
    if (marks >= 40) System.out.println("Pass");
  }
}

Output: Asha scored 72 then Pass. Real Main. Swap marks/name to show one idea from Custom Exception in Java.

How to Explain Custom Exception in Java to an Interviewer

When do you make a custom exception?

Business rule Clear name for the caller

Exception vs RuntimeException parent?

Exception = checked RuntimeException = unchecked