Difference between code in JavaScript finally block and after try ... catch

510 Views Asked by At

This question may appear similar to others that have been answered, but I can't find an answer relating to JavaScript.

What is the difference between code in a finally block and code that comes after the entire try ... catch ... finally statement?

That is, what is the difference between this code:

try {
  f(x);
}
catch(e) {
  g(e);
}
finally {
  h(y);
}

and this code:

try {
  f(x);
}
catch(e) {
  g(e);
}
h(y);
2

There are 2 best solutions below

2
CertainPerformance On BEST ANSWER

One difference is that, if a value is returned in a finally, it will override values returned from inside the prior try and catch blocks:

function foo() {
  try {
    throw new Error('1');
  } catch(e) {
    return '2';
  } finally {
    return '3';
  }
}
console.log(foo());

Returning from a finally will also prevent throws in a try or catch from percolating outward - instead, only the finally's normal return completion value will be the result.

(function() {
  try {
    try {
      throw new Error('oops');
    } catch (ex) {
      console.error('inner', ex.message);
      throw ex;
    } finally {
      console.log('finally');
      return;
    }
  } catch (ex) {
    // not entered into
    console.error('outer', ex.message);
  }
})();

0
Alexander Nied On

I'll admit this question had me scratching my head at first. But a look at the MDN reference for try...catch includes this salient section on "Returning from a finally-block". It appears that if you return from a finally block, it will override anything returned or thrown from the preceding try or catch blocks. So while your example may be identical, if you were to change it to this:

try {
  return f(x);
}
catch(e) {
  throw g(e);
}
finally {
  return h(y);
}

...it would fundamentally differ from this:


try {
  return f(x);
}
catch(e) {
  throw g(e);
}
return h(y);