Sam H
Sam H

Reputation: 561

How do I throw error in one function to be caught by another function?

I have this "test" code:

function func1(){
    try{
    ...stuff...
    }catch(err){
        throw new Error();
    }
}

function func2(){
    try{
        func1();
    }catch(err){
        console.log("ERROR")
    }
}

func2();

I have a function that throws an error in the catch in a try-catch-statement. I want it to, if func1 throws Error, it gets caught by the first try-catch-statement, but when I try this, it doesn't get caught by the first statement, it just pauses the code and returns the error. What have I done wrong? and is this the wrong way to do it?

Upvotes: 9

Views: 16247

Answers (3)

Krishna Prashatt
Krishna Prashatt

Reputation: 649

There is no need for a separate try/catch block in func1 because, it is already within the error handler of func2. In this case, whatever error you throw from func1 will automatically caught by func2

function func1() {
    throw new Error('oops');
}

function func2() {
  try {
    func1();
  } catch(err) {
    alert(err.message);
  }
}
    
func2();

Upvotes: 3

Daniel Cottone
Daniel Cottone

Reputation: 4480

This code should give you an idea of how try/catch blocks work. In the first function call, we call func2 which has a try/catch block. You can see in the console that the error is caught and execution continues. Then we call func1 which throws an uncaught error, which shows up in the console as an error.

function func1() {
  console.log('func1...');
  throw new Error('something bad happened!');
}

function func2() {
  console.log('func2...');
  try {
    func1();
  } catch (err) {
    console.log('Caught error');
  }
}

console.log('func2()');
func2();

console.log('func1()');
func1();

Upvotes: 7

Sagiv b.g
Sagiv b.g

Reputation: 31024

Not sure exactly where you are stuck but this should work:

Make sure you check your real console

function func1() {
  try {
    throw new Error('hi from func1')
  } catch (err) {
    throw err;
  }
}

function func2() {
  try {
    func1();
  } catch (err) {
    // this doesn't work in stack snippets console
    // hit f12 to see your real console
    console.log('catched in func2', err)
  }
}

func2();

Upvotes: 1

Related Questions