Published at
Updated at
Reading time
1min

Today I woke up checked Slack and saw a little trick question by my friend Tomasz in one of the JavaScript channels.

function f() {
  try {
    return 'A';
  } finally {
    return 'B';
  }
}

f(); // ?

I don't use the finally block in try/catch statements very often so I was not sure what the return value will be for this snippet. It turns out the finally block goes over everything according to MDN:

If the finally block returns a value, this value becomes the return value of the entire try-catch-finally production, regardless of any return statements in the try and catch blocks.

So let's have a look at a few examples:

function f() {
  try {
    return 'A';
  } finally {
    return 'B';
  }
}

f(); // 'B'

// ***********************************************

function g() {
  try {
    throw new Error( 'Foo' );
  } catch( e ) {
    return 'A';
  } finally {
    return 'B';
  }
}

g(); // 'B'

// ***********************************************

function h() {
  try {
    throw new Error( 'Foo' );
  } finally {
    return 'B';
  }
}

h(); // 'B' (without throwing an exception)

// ***********************************************

function i() {
  try {
    throw new Error( 'Foo' );
  } catch( e ) {
    throw new Error( 'Bar' );
    return 'A';
  } finally {
    return 'B';
  }
}

i(); // 'B' (without throwing an exception)

finally overwrites return statements and also "catches" exceptions. Good to know. ;)

If you enjoyed this article...

Join 6.3k readers and learn something new every week with Web Weekly.

Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles