Find the bug · #68 · Errors and security Easy Java
Saving always says “saved”
A profile save reports success even when it rejects the profile.
On this page
The report
Saving a profile without an email should show “email is required”. Instead the app says “Saved”, and the profile silently isn’t.
The code
Read it first: what should it do? Then click the line where you think the bug is.
class Saver {
// Saves the profile and returns true; errors must reach the caller.
static boolean save(Map<String, String> profile, List<String> log) {
try {
if (!profile.containsKey("email")) throw new IllegalArgumentException("email is required");
log.add("saved " + profile.get("email"));
} finally {
log.add("save attempted");
return true;
}
}
}Read it, then pick a line.
What happens to an exception that is on its way out when the finally block says return?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
List<String> log = new ArrayList<>();
try {
System.out.println(Saver.save(new HashMap<>(), log));
} catch (IllegalArgumentException e) {
System.out.println("error: " + e.getMessage());
}It prints
true
It should print
error: email is required
Show the answer: the bug, the fix, and how you’d find it
The bug (line 9)
Line 9 returns from inside finally. A finally block runs even while an exception is on its way out, and a return there replaces the exception: it is thrown away and the method returns true. Return from the try, and keep finally for clean-up only.
The fix
4 try {5 if (!profile.containsKey("email")) throw new IllegalArgumentException("email is required");6 log.add("saved " + profile.get("email"));7 return true;7 } finally {8 log.add("save attempted");9 return true;10 }11 }12}How you’d find it
- Reproduce with a profile that has no email:
true, no exception. - The exception is definitely thrown (put a log before the
throw), so something swallows it. There is nocatch, only afinally. - A
returninfinallyoverrides any exception. Java even warns about it: “finally block does not complete normally”.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
boolean threw = false;
try {
Saver.save(new HashMap<>(), new ArrayList<>());
} catch (IllegalArgumentException e) {
threw = true;
}
check(threw, "the error reaches the caller");
check(Saver.save(new HashMap<>(Map.of("email", "a@b.co")), new ArrayList<>()), "a good profile saves");Where else this bites
- JavaScript and Python behave the same way: a
returninfinallyswallows the error. - A
breakorcontinueinfinallydoes it too.