Search code examples
javascripttry-catchtry-catch-finallytry-finally

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


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);

Solution

  • 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);
      }
    })();