DEV Community

Matt Crowder
Matt Crowder

Posted on

1

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.

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay