BackendBench
Coffee
Spot the Bug #62

Optional.get without checking

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

easyNull handlingbuggy line: 7

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

What is wrong

Optional.get throws NoSuchElementException when the value is absent, which just moves the unchecked failure from null to an exception. The type signalled that a missing value was possible and the code ignored it.

The fix

return repo.findEmail(id).orElseThrow(() -> new IllegalArgumentException("no account " + id));

How to avoid it next time

Use orElse, orElseGet, orElseThrow, map or ifPresent. Avoid get unless you have just checked isPresent.

Want the background? Read Optional and null safety in the Java concepts library.

About null handling

NullPointerException is still the most common production exception. Chained calls, auto-unboxing, maps that return null for missing keys and Optional used the wrong way all hide a null until the worst moment.

In code review: Trace each dereference back to where the value comes from and decide whether it can be null. Be wary of Optional.get, getOrDefault on null values and unboxing of Integer fields.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #61#63 โ†’

Frequently asked questions

What is the bug in "Optional.get without checking"?

Optional.get throws NoSuchElementException when the value is absent, which just moves the unchecked failure from null to an exception. The type signalled that a missing value was possible and the code ignored it. The faulty line is line 7: return repo.findEmail(id).get();

How do I fix it?

Replace it with: return repo.findEmail(id).orElseThrow(() -> new IllegalArgumentException("no account " + id));. Use orElse, orElseGet, orElseThrow, map or ifPresent. Avoid get unless you have just checked isPresent.

How do I catch null handling in code review?

Trace each dereference back to where the value comes from and decide whether it can be null. Be wary of Optional.get, getOrDefault on null values and unboxing of Integer fields.

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