Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!