💻

Finally Blocks

Created
Nov 30, 2021 4:47 AM
Tags
software

What do you expect the below code block to print out?

try {
  console.log('try run');
  throw new Error('try error');
} catch (error) {
  console.log('catch run');
  throw new Error('catch error');
} finally {
  console.log('finally run');
}
console.log('after finally run');

I expected:

try run
catch run
JS error ('catch error')

But it actually results in:

try run
catch run
finally run
JS error ('catch error')

It was surprising to me at first that finally has this behavior since I always assumed finally blocks were syntactic sugar. Turns out they actually serve a purpose!