- I got "Uncaught SyntaxError: Invalid or unexpected token" error.
And try to catch with 'try ~ catch' but it's not working.
function a(){ try{ var img1 = "==""; <#-- it occurs error --> }catch (e) { console.log("image error:" + e.message); } }
1 Answer
You have a syntax error and you can not catch a syntax error.
This error is checked at the parsing or validation time of your code. The try .. catch statement is executed at the running time. And because of this it was not functioning.
If you eval or parse (for ex. JSON) your code you can handle syntax errors only. Or you can create a syntax error like this:
try {
throw new SyntaxError('Hello', 'someFile.js', 18);
} catch (e) {
console.log(e.message); // "Hello"
console.log(e.name); // "SyntaxError"
}
For the eval handled or by self created syntax errors:
A SyntaxError is thrown when the JavaScript engine encounters tokens or token order that does not conform to the syntax of the language when parsing code.
From MDN
Try this:
function a(){
try{
var img1 = "==\"";
//but you have to put some error here without parsing or validation error of your code.
}catch (e) {
console.log("image error:" + e.message);
}
}
I would like to recommend you read:
try .. catchis executed at the running time, which will never take place because a syntax error has interrupted the script.