Reputation: 33
I was trying few examples about exception handelling in javascript using nested try..catch. The code within the inner try block throws an error but instead of the inner catch block handelling the code, the exception is being caught by the outer catch block. I didnt understand that part
This i read on the MDN documentation but it doesnt go with the example i tried:
"Any given exception will be caught only once by the nearest enclosing catch-block unless it is re-thrown. Of course, any new exceptions raised in the "inner" block (because the code in catch-block may do something that throws), will be caught by the "outer" block".
function a() {
try {
d()
function d() {
try {
let user = "hello"
let user = {name: 'bruce'}
} catch (err) {
console.log(err, "inside the function err")
}
}
} catch (err) {
console.log(err, "Error caught")
}
}
a()
The error:
SyntaxError: Identifier 'user' has already been declared, 'Error caught'
Considering the above statement error should be caught in inner catch block then why is it getting caught in the outer catch block I expected the error should be caught inside the 'inner catch block'(i.e, err,"inside the function err") but instead its getting caught by the 'outer' one (i.e,err,"Error Caught").
Upvotes: 1
Views: 954
Reputation: 7949
Here in your snippet , When you declare let user
, let allows you to declare variables that are limited to a scope of a block statement, or expression on which it is used, unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
When you keep the same variable name , it is considered an error when the program compiles , while try catch
detects the error at run-time
. Therefore , your program does not get compiled fully and it gives the error at compile time due to duplicate variable name
.
Hope you get the point .
Instead try out the following code .
function a() {
try {
d()
function d(user) {
try {
JSON.parse(user);
} catch (err) {
console.log(err, "inside the function err")
}
}
} catch (err) {
console.log(err, "Error caught")
}
}
a()
It will give you your expected output .
Upvotes: 1