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?
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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With