如何在JavaScript中捕获SyntaxError

时间:2015-07-02 11:17:35

标签: javascript exception-handling syntax-error

我试图在我的代码中捕获语法错误,但它没有进入catch块

( function(){
try {

 throw fn(){};  // I am trying to generate some syntax error here

}catch (exception){
    console.log(exception.message);
  }

})();

被修改

如果你注意到这里错误的语法在try块里面,所以作为一个javascript理论它必须首先进入catch块,然后是什么内置对象使用SyntaxError

( function(){
try {

throw fn(){};
}catch (exception){
   if(exception instanceof SyntaxError)
   console.log("Syntax Exception occured" + exception.message); 
}
})();

但这不是在程序中处理,而是我可以直接在控制台中看到“Uncaught SyntaxError”

Uncaught SyntaxError: Unexpected token {
    at Object.InjectedScript._evaluateOn (<anonymous>:895:140)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
    at Object.InjectedScript.evaluate (<anonymous>:694:21)

1 个答案:

答案 0 :(得分:1)

您无法捕获语法错误只是因为未评估整个脚本(由于语法错误... 我唯一可以想象的是将代码作为字符串,然后将其传递给eval()并将eval包装成try catch ......

但如果你这样做,地球就会崩溃......

var test="var x= 1.5.5;"; //this is a syntax error
var test2="var x=1;"
try {
  eval(test)
  alert(test + ' is a valid script')
} catch(e) {
  alert(test + ' is not a valid script')
}
try {
  eval(test2)
  alert(test2 + ' is a valid script')
} catch(e) {
  alert(test2 + ' is not a valid script')
}