BackendBench
Coffee
Spot the Bug #39

A finally block that overrides the failure

A hard Java puzzle in the exception handling mistakes family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

hardException handling mistakesbuggy line: 8

Highlighted: line 8. Play this one as a puzzle without the answer.

What is wrong

A return statement in finally replaces whatever the try or catch block was doing, including a thrown exception. The invalid port is silently turned into 8080, and the exception disappears. The compiler only warns.

The fix

} finally { /* cleanup only, never return or throw here */ }

How to avoid it next time

Use finally for cleanup only. Never return, break or continue out of it, and treat the compiler warning as an error.

Want the background? Read Exceptions: try, catch, throw in the Java concepts library.

About exception handling mistakes

Swallowed exceptions, lost causes and returns in finally blocks hide failures until the data is already wrong. The program keeps running and nobody knows why the result is missing.

In code review: An empty catch block, a catch that only prints, or an exception rethrown without its cause are all red flags. Log with the exception object and rethrow or handle meaningfully.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #38#40 โ†’

Frequently asked questions

What is the bug in "A finally block that overrides the failure"?

A return statement in finally replaces whatever the try or catch block was doing, including a thrown exception. The invalid port is silently turned into 8080, and the exception disappears. The compiler only warns. The faulty line is line 8: return 8080;

How do I fix it?

Replace it with: } finally { /* cleanup only, never return or throw here */ }. Use finally for cleanup only. Never return, break or continue out of it, and treat the compiler warning as an error.

How do I catch exception handling mistakes in code review?

An empty catch block, a catch that only prints, or an exception rethrown without its cause are all red flags. Log with the exception object and rethrow or handle meaningfully.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need