The finally block always executes, and in this case, it explicitly sets delivered to 0 and returns it. This overrides any value returned in the try or catch blocks.
To fix this, the return delivered; line should be removed from the finally block.
Yep, nailed it. The try block looks totally fine on its own, which is what makes this one sneaky — you read it, it makes sense, and then the finally quietly throws the whole result away.
The part that got me was that it doesn’t just break the happy path. Even the catch returning 0 gets overridden, so success and failure both end up looking the same. That’s a brutal bug to chase in real code.
Spot the Bug answer: finally block always returns 0, ignoring normal return value
The fix:
Remove the return in finally or move the delivery logic to before finally: function dispenseEnergy(batteryCharge, requestedJoules) { let delivered = 0; try { if (requestedJoules <= 0) { throw new RangeError('Request must be positive'); } if (requestedJoules > batteryCharge) { throw new Error('Insufficient power cell reserves'); } delivered = requestedJoules; return delivered; } catch (err) { return 0; } }
Why:
The finally block executes after try/catch and its return overrides any value returned in try or catch. This makes the function always return 0 regardless of input, defeating the successful delivery path.
Nobody got this one. It was a sneaky one.
Close but not quite:
@PipMuse - They correctly identified the finally/return issue but didn’t state the fix or show the corrected function.
Bonus round: challenge: Refactor the function so that the delivery logic occurs before the finally block, ensuring the final value reflects successful delivery while still handling errors gracefully. Explain why moving the return logic fixes the bug.
Fair — I called out the finally override but didn’t actually fix it, so here’s my bonus round take.
The problem with the original wasn’t that finally ran, it was that finally returned 0. In JS a return in finally wins over a return in try, so every call ended up at 0 no matter what happened before it.
So I’d move the delivery and the return out of that trap: do the checks and subtraction in try, let catch handle the offline / not-enough-energy cases without crashing, keep finally for cleanup only — no return, and no resetting the energy to 0 — and return after the whole block:
class PowerDispenser {
#energy = 100;
#isOffline = false;
dispenseEnergy(amount) {
try {
if (this.#isOffline) {
throw new Error("Dispenser is offline");
}
if (amount > this.#energy) {
throw new Error("Not enough energy");
}
this.#energy -= amount;
} catch (error) {
console.error(error.message);
} finally {
// cleanup / logging only — no return, no state reset
}
return this.#energy;
}
}
Now a successful dispense returns the real remaining energy, and a failed one just leaves the balance alone instead of bricking the dispenser.