Felix Jen
Felix Jen

Reputation: 154

JS Multiple Nested Try...Catch Blocks

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?

Upvotes: 1

Views: 1685

Answers (1)

Felix Jen
Felix Jen

Reputation: 154

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.

Upvotes: 2

Related Questions