liveBook · Manning

Empty catch block

As explained in The Art of Code

An empty catch block is an exception handler whose body performs no operation or explanation when an exception is caught.

An empty catch block catches an exception and then says nothing: no recovery, propagation, logging, or explanation. It quietly hides a failure, turning an unexpected condition into an invisible one. Assumptions that an exception “will never happen” can be invalidated by later changes, leaving a difficult-to-find defect. section 7.2.4

try {
  int parsedNumber = Integer.parseInt(data);
} catch (NumberFormatException exception) {
}

Parsing failure is intercepted but discarded, so invalid input produces neither a result nor an account of what went wrong. section 7.2.4

Treat an empty handler as a code smell. Static analysis tools such as SonarQube can flag it, but the more important question is what the failure path should mean: recover, propagate, report, or redesign the API so callers receive a meaningful result. section 7.2.4

Rarely, a failure may already represent the desired end state. Even then, make that intent explicit:

  • Comment why ignoring the exception is safe, such as deleting a temporary file already removed or closing an already-closed connection. section 7.2.4
  • Reconsider an API that repeatedly forces callers to ignore exceptions; a return type such as Optional or boolean may better express nonexceptional outcomes. section 7.2.4

How The Art of Code covers it

How deep it goes
Defines the antipattern, explains its risks and rare exception cases, and defers broader API redesign details.
Examples
Uses ignored NumberFormatException, deletion of an absent temporary file, and closure of an already-closed connection.
What it assumes
Assumes familiarity with exceptions while defining empty catch blocks through a small try/catch example.
What you can do after
Evaluate/understand whether a caught exception needs recovery, propagation, reporting, documentation, or an API redesign.
How it connects
Connects exception handling with static analysis, API design, Optional, and boolean return types.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Art of Code. The section links point to the parts of the book it draws on.