loading...

What happens when you only write try/finally

mcrowder65 profile image Matt Crowder ・1 min read

I thought to myself today, hm, what happens when you do try/finally, and don't have a catch clause, so, what is the output here?

const errorThrower = () => {
  throw new Error("i am an error");
};

const errorInvoker = () => {
  try {
    errorThrower();
    console.log("errorInvoker");
  } finally {
    console.log("finally");
  }
};

const catcher = () => {
  try {
    errorInvoker();
    console.log("catcher");
  } catch (error) {
    console.log("catcher caught the error");
  }
};

catcher();

I thought that the output would be:

finally
catcher

But actually the output is:

finally
catcher caught the error

In errorInvoker, the try block executes, and errorThrower() throws an error, and then immediately after the error is thrown, the finally executes, then catcher catches the error that errorThrower threw, and logs catcher caught the error.

Posted on by:

mcrowder65 profile

Matt Crowder

@mcrowder65

Software Engineer at Appian, previously at Walmart Labs. Co-organizer of novajavascript.com, public speaker, teacher, codementor.io/mcrowder65

Discussion

pic
Editor guide