Java · OOP, JVM and backend craft
How does exception handling work in Java?
Short answer
Java represents failures as Throwable subclasses, split into Error and Exception. Use try, catch and finally to handle recoverable failures and guarantee cleanup.
Throwable has two main branches. Error covers serious JVM-level problems such as OutOfMemoryError and StackOverflowError, which applications normally cannot recover from. Exception covers application-level failures, and RuntimeException marks the unchecked branch.
try {
int result = Integer.parseInt(input);
System.out.println(result);
} catch (NumberFormatException error) {
System.out.println("Invalid number: " + error.getMessage());
} finally {
System.out.println("done");
}Good handling practice
- Catch the most specific exception you can handle
- Do not swallow an exception or leave an empty catch block
- Wrap lower-level exceptions and preserve the cause
- Use multi-catch when several exceptions share the same handling
- Avoid using exceptions for ordinary control flow
A stack trace is expensive because it captures the call stack. Throwing in a tight loop for expected conditions hurts performance and obscures intent. Validate inputs and return a result type when absence is normal; reserve exceptions for exceptional conditions.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between Error and Exception?
- 2Why is an empty catch block dangerous?
- 3When should you wrap an exception?
- 4Why should you avoid return in finally?
Say it in the interview
Java separates Throwable into Error for JVM-level failures and Exception for application failures. I use try and catch around the specific failure I can handle, and finally for cleanup. I never swallow exceptions silently; if I translate one, I keep the original as the cause. I also avoid exceptions for normal control flow because stack traces are costly and the intent becomes unclear.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Java mock interview and get scored feedback on depth, clarity and confidence.