1

I have a function which needs to perform multiple promises in a strict order, and if any one were to fail, the whole function needs to error out. I'm understanding that I should use a Try...Catch block to catch any exceptions which get thrown.

Currently, I am using a nested try...catch like:

try {
  try {
    code1()
  } catch(err) {
    console.log("Inner 1 ", err)
    throw err
  }

  try {
    code2()
  } catch(err) {
    console.log("Inner 2 ", err)
    throw err
  }
} catch(err) {
  console.log("Outer", err)
} finally {
  console.log("Full Success")
}

The intention here is that if either code1() or code2() were to fail, the outer catch would trigger. If both code1 and code2 were to success, the outer finally block would trigger.

However, it seems, right now, no matter if code1 or code2 succeed, the outer finally is always being trigger in addition to the associated inner catch statements.

Is there any way to get the outer catch to trigger?

5
  • 2
    finally executes no matter what happens inside. Commented Nov 22, 2021 at 22:58
  • @Barmar Oh heck... my readings of the docs made me believe it only executed on success... Commented Nov 22, 2021 at 23:00
  • 1
    From MDN: Statements that are executed after the try statement completes. These statements execute regardless of whether an exception was thrown or caught. Commented Nov 22, 2021 at 23:03
  • @Barmer Yep, realized my mistake after re-reading. I stopped at the first sentence... Commented Nov 22, 2021 at 23:23
  • Python has what you wanted in its else: block. Commented Nov 22, 2021 at 23:26

1 Answer 1

2

Turns out, thanks to @Barmar 's comment, the finally block will always execute, that's why my code was always throwing the finally. Instead, I moved the "full success" into the outer try block.

try {
  try {
    code1()
  } catch(err) {
    console.log("Inner 1 ", err)
    throw err
  }

  try {
    code2()
  } catch(err) {
    console.log("Inner 2 ", err)
    throw err
  }

  console.log("Full Success")
} catch(err) {
  console.log("Outer", err)
}

Now, it appears to be working as intended.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.