- 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); } }
- 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); } }
- 6 Is that your exact code? Also you can't catch syntax errors (outside of eval at least). – TiiJ7 Commented Jun 26, 2018 at 7:55
- I occurs error Intentionally to test catch statement. But it can't catch the error. – jumi lee Commented Jun 26, 2018 at 7:58
- 1 AFAIK syntax error is not exception – Terry Wei Commented Jun 26, 2018 at 7:59
-
Syntax errors are checked at the parsing time,
try .. catch
is executed at the running time, which will never take place because a syntax error has interrupted the script. – Teemu Commented Jun 26, 2018 at 7:59 - 2 Possible duplicate of Can syntax errors be caught in JavaScript? – Aayush Sharma Commented Jun 26, 2018 at 8:13
1 Answer
Reset to default 5You 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 remend you read:
try...catch
StatementException Handling State
Syntax Error
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744842586a4596648.html
评论列表(0条)