Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does catch in the calling function is never executed?

I have a simple use case that I want to execute a statement inside the catch blog inside catch block of calling function. Somehow in my code there is no execution of catch block statement inside calling function

async function main() {

  try {
    console.log('jatin')
    const hello = await second()
    console.log(hello) //ok
    console.log('yes boy') //ok
  } catch (e) {
    console.log('cm') //not ok
    console.log(e) //not ok
  }
}

async function second() {
  try {
    console.log('in second') //ok
    throw new Error()
  } catch (error) {
    console.log('trial') //ok
    console.log(error) //ok
    return error
  }
}

main()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You already caught the Error in the second function. If you want it to propagate back to the caller, you would need to rethrow it (or don’t catch it in the first place).

async function main() {
  try {
    console.log('main');
    const hello = await second();
    console.log(hello);
  } catch (e) {
    console.log('catch block of main');
    console.log(e);
  }
}

async function second() {
  try {
    console.log('second');
    throw new Error();
  } catch (error) {
    console.log('catch block of second');
    console.log(error);
    throw error;
  }
}

main();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading