Exceptions for Control Flow Anti-Pattern
Fast recall
Quick revision
Core answer
Understanding of exception performance cost and semantic intent — does the candidate know when exceptions are appropriate
Using catch(NoSuchElementException) to check if a collection is empty — treating exceptions as if-statements
Explain stack trace capture cost with numbers and give a concrete better alternative using Optional or if-checks
Interview-ready guide
Interview answer
I avoid exceptions as a substitute for an ordinary branch. For example, I check isEmpty() rather than calling getFirst() and catching NoSuchElementException as the normal empty result. The direct form is clearer, and throwing an exception usually captures diagnostic state and unwinds the stack.
I would not state a universal speed multiplier or ban exceptions from every expected failure. Some APIs deliberately report invalid input or a failed operation with an exception. The important distinction is whether I am following a failure contract or using throw and catch as a disguised if statement.
Exceptions for Control Flow Anti-Pattern
Direct Answer
Do not use exceptions for an ordinary, frequent branch when the API can represent that outcome directly. Throwing normally captures diagnostic state and unwinds the stack, and it also hides the expected control flow. Exceptions are still correct for failures defined by an API; the issue is using them as a substitute for a normal condition, not an absolute ban.
Common Mistakes & Pitfalls
- Exception as Null Check: Using try-catch
NullPointerExceptioninstead ofif (obj != null)— this is thousands of times slower and completely unclear to readers what you're checking. Every NPE costs microseconds in stack trace creation for what should be a nanosecond comparison. - Exception for Empty Check: Using
catch (NoSuchElementException)orcatch (IndexOutOfBoundsException)to detect empty collections — just callisEmptyor useOptionalinstead. - Exception for Validation: Throwing
NumberFormatExceptionto check if a string is numeric, then catching it — use a regex or try-parse pattern withOptionalinstead. This creates unnecessary exception objects on every invalid input, which in a web form validation scenario means exceptions on every user typo.
Check your understanding
Answer these without looking back at the article.
- What is the performance cost of creating an exception in Java?
- How does Optional solve the 'check if value exists' use case?
- Can you suppress the stack trace to make exceptions cheaper?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.