Spot the bug - #187: Power Dispenser

Something subtle goes wrong inside this quirky energy dispenser logic.

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;
  } finally {
    delivered = 0;
    return delivered;
  }
}

Reply with what is broken and how you would fix it.

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.