Interview Questions
Exception Handling · Study material
Java Exception Handling – Interview Questions
1. What is an exception?
An event during execution that disrupts the normal flow of instructions, represented by a Throwable object.
2. Error vs Exception?
Errors are serious JVM-level problems applications should not catch; Exceptions are conditions a program may handle.
3. Checked vs unchecked exceptions?
Checked exceptions must be caught or declared; unchecked ones (RuntimeException, Error) need not be.
4. throw vs throws?
throw raises an exception object; throws declares exceptions a method may pass to its caller.
5. What is finally?
A block that always runs after try (and catch), used for clean-up.
6. When does finally not run?
If the JVM exits (System.exit), crashes, or the thread is killed, or try never finishes.
7. Can we have try without catch?
Yes, with finally or as try-with-resources.
8. What is multi-catch?
catch (A | B e) handles several unrelated exception types in one block; e is effectively final.
9. Why must subclass catch blocks come first?
A superclass catch would already handle the subclass, making the later block unreachable – a compile error.
10. What is try-with-resources?
A try that declares AutoCloseable resources and closes them automatically in reverse order.
11. What are suppressed exceptions?
Exceptions from close() that are attached to the primary exception in try-with-resources.
12. How do you create a custom exception?
Extend Exception (checked) or RuntimeException (unchecked) and provide constructors that call super(message[, cause]).
13. What is exception chaining?
Wrapping one exception in another while keeping the original as its cause.
14. What happens if an exception is not caught?
It propagates up the call stack; if main does not catch it, the thread ends and a stack trace is printed.
15. What if both try and finally return a value?
The value from finally wins and any exception from try is discarded.
16. Can an overriding method throw broader checked exceptions?
No; only the same, narrower or none (unchecked ones are always allowed).
17. What is the difference between final, finally and finalize?
final is a modifier, finally a clean-up block, finalize a deprecated Object method.
18. What are assertions?
assert statements that check internal assumptions and throw AssertionError when enabled with -ea.
19. Is catching Exception bad?
It is acceptable at top-level boundaries (to log and respond), but elsewhere it hides bugs and unrelated failures.
20. Name common unchecked exceptions.
NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException, ClassCastException, NumberFormatException, IllegalArgumentException, IllegalStateException.