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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay