Exceptions in Java
An exception is an object Java creates and propagates up the call stack when normal flow breaks: a file will not open, a null is dereferenced, memory runs out. A method that cannot cope does not return an error code — it throws, and control jumps to the nearest matching catch, unwinding the stack on the way. With no handler, the thread terminates and the trace is printed.
What Java separates from a plain "something failed": some exceptions the compiler forces you to plan for at compile time (checked), and some it does not (unchecked). That split decides where you must write a catch or a throws, and where a failure honestly shoots all the way to the top. Two things almost always come with it: the difference between throw (raise now) and throws (declare in the signature), and try-with-resources, which closes resources for you. The full map is in the layers below.
Topic map
- Checked vs Unchecked —
Exceptionsubclasses vsRuntimeExceptionandError; who the compiler forces you to handle and who it does not. - throw vs throws — the statement that raises an exception vs the signature clause that declares one.
- try-with-resources — automatic
close()in reverse order,AutoCloseable, and suppressed exceptions.
Common traps
| Mistake | Consequence |
|---|---|
Treating Error and RuntimeException as checked | The compiler never requires declaring them; no throws is needed |
Catching a broad Exception in an empty catch to silence the compiler | The failure is lost unhandled — the bug surfaces later, with no trace |
Writing throws in the body and throw in the signature | Confusing the statement with the clause — the code will not compile |
Releasing a file or stream by hand in finally instead of try-with-resources | Easy to forget close() or lose the original exception under a close failure |
| Expecting resources to close in opening order | try-with-resources closes them in REVERSE order |
| Using exceptions for ordinary control flow | fillInStackTrace at construction walks the whole stack — orders of magnitude slower than a branch |
Interview relevance
Exceptions come up on almost every Java interview, but the check is not a list of subclasses — it is your model: what the compiler forces you to plan for, who owns resource release, and how "raise" differs from "declare".
Typical checks:
- The checked/unchecked split and where it runs through the class hierarchy.
- The difference between
throwandthrows. - What try-with-resources does and what interface a resource needs.
- The order resources close in and what a suppressed exception is.
- Why exceptions are costly as a replacement for an explicit condition check.
Common wrong answer: "RuntimeException is checked, it needs a throws." That opens the discussion that checkedness is decided by position in the hierarchy (Exception minus RuntimeException), not by severity, and that the compiler requires nothing for RuntimeException and Error.