catch 语句可以捕获 JavaScript 中的语法错误吗?
Kangax 博客有一个代码示例:§
try {
(var x = 5); // grouping operator can only contain expression, not a statement (which `var` is)
} catch(err) {
// SyntaxError
}
第2行的语法错误会影响“整个代码的语法”,这里的catch
语句有什么意义?
catch
能够捕获 JavaScript 中的语法错误吗?
Kangax blog has a code example: §
try {
(var x = 5); // grouping operator can only contain expression, not a statement (which `var` is)
} catch(err) {
// SyntaxError
}
Since the syntax error at line 2 would affect the "syntax of the entire code", what's the point of the catch
statement here?
Is catch
able to catch syntax errors in JavaScript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你是对的,javascript 解析器会生成一个错误,所以它永远不会捕获它。
http://jsbin.com/oluje5/edit
也许他的意图是指出错误的语法(分组运算符只能包含表达式,不能包含语句),但try/catch语句没有用。
此外,catch 中的注释
//syntaxError
让我们假设 catch 会执行某些操作。You are right, javascript parser will generate an error, so it will never catch it.
http://jsbin.com/oluje5/edit
Maybe his intention was to point out the wrong syntax (grouping operator can only contain expression, not a statement), but the try / catch statement is useless.
Moreover, the comment
//syntaxError
inside catch let suppose that the catch will do something.不,这是正确的。使用
try...catch
无助于解决语法错误。如果存在语法错误导致脚本块无法被解析,则脚本块根本不会运行。
No, that is correct. Using a
try...catch
doesn't help against syntax errors.The script block won't run at all if there is a syntax error keeping it from being parsed.
try/catch 不会捕获语法错误,因为您不能像这样将变量赋值包含在括号中。
Syntax errors wont be caught by try/catch, as you can't wrap variable assignments in brackets like that.