DEV Community

Matt Crowder
Matt Crowder

Posted on

What happens when you only write try/finally

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

Enter fullscreen mode Exit fullscreen mode

I thought that the output would be:

finally
catcher
Enter fullscreen mode Exit fullscreen mode

But actually the output is:

finally
catcher caught the error
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)