Finally Overrides Returns From Try And Catch

finally always runs after try or catch, a return written inside it replaces the value already computed, and local changes there cannot alter a settled result.

JavascriptResilience

Code

javascriptsnippet
41 lines
function readSetting(settings, key) {
  try {
    if (!(key in settings)) {
      throw new Error('missing key: ' + key);
    }
    return 'value=' + settings[key];
  } catch (error) {
    return 'fallback after ' + error.message;
  } finally {
    // finally 无论 try 还是 catch 离开都会执行
    console.log('finally runs for', key);
  }
}

const settings = { retries: 3 };
console.log(readSetting(settings, 'retries'));
console.log(readSetting(settings, 'timeout'));

// finally 里的 return 会覆盖 try/catch 已经算好的返回值
function pick(flag) {
  try {
    if (flag) return 'from try';
    throw new Error('boom');
  } catch {
    return 'from catch';
  } finally {
    return 'from finally';
  }
}
console.log(pick(true), '|', pick(false));

// 只清理不返回:finally 不改变返回值
function tally() {
  let result = 0;
  try {
    return (result = 41) + 1;
  } finally {
    result += 1; // 修改局部变量不影响已经确定的返回值
  }
}
console.log('tally:', tally());

Output

Captured from a sandboxed run of this snippet in the build pipeline.

finally runs for retries
value=3
finally runs for timeout
fallback after missing key: timeout
from finally | from finally
tally: 42

What the code does

Everything happens inside the functions readSetting, pick and tally.

Invalid states are rejected up front: it throws Error instead of continuing with bad data.

What to watch for

  • The package manager never enters the picture for this snippet.
  • The guard flag short-circuits the flow with an early return when its condition holds.

Applying it

The main signature reads function readSetting(settings, key)

Each run prints the 2 labeled blocks finally runs for, tally: in source order.

Statements that matter

return 'from finally';
return 'fallback after ' + error.message;
throw new Error('missing key: ' + key);

Interactive Tools for This Topic

FAQ

How are precondition violations signaled?
The code throws `Error` — the guard `flag` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. The file defines `readSetting`, `pick`, `tally` at load time.