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").
leterror happens at parse time, not execution time so it throws before you're inside the innertry. Another possibility, the try block isn't an actual block scope so the twoletstatements are hoisted to the top of the first block ind()and thus the doubleleterror occurs before thetrystatement.