Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 454
Sam H Avatar asked Apr 29 '19 10:04

Sam H


Video Answer


2 Answers

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();
like image 150
Daniel Cottone Avatar answered Sep 21 '22 06:09

Daniel Cottone


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();
like image 41
Krishna Prashatt Avatar answered Sep 20 '22 06:09

Krishna Prashatt