jum*_*lee -2 javascript error-handling try-catch uncaughtexceptionhandler
并尝试使用“try ~ catch”进行捕获,但它不起作用。
function a(){
try{
var img1 = "==""; <#-- it occurs error -->
}catch (e) {
console.log("image error:" + e.message);
}
}
Run Code Online (Sandbox Code Playgroud)您有语法错误,但无法捕获语法错误。
在解析或验证代码时会检查此错误。该try .. catch
语句在运行时执行。因此它无法发挥作用。
如果您评估或解析(例如 JSON)您的代码,您只能处理语法错误。或者您可以创建如下语法错误:
try {
throw new SyntaxError('Hello', 'someFile.js', 18);
} catch (e) {
console.log(e.message); // "Hello"
console.log(e.name); // "SyntaxError"
}
Run Code Online (Sandbox Code Playgroud)
对于eval
已处理或自行创建的语法错误:
当 JavaScript 引擎在解析代码时遇到不符合语言语法的标记或标记顺序时,会抛出 SyntaxError。
来自MDN
尝试这个:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我想推荐您阅读: