2015-07-02 28 views
0

我試圖抓住一個語法錯誤在我的代碼,但如果您發現此錯誤的語法是它不進入catch塊如何捕捉一個SyntaxError在JavaScript

(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); 
} 
})(); 

但這不是在程序處理,而不是我能看到「未捕獲的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

使用'jslint' http://www.jslint.com/ – Tushar

+0

可能重複的[語法錯誤可以在JavaScript中被捕獲?](http://stackoverflow.com/questions/5963045/syntax-errors-can-被抓住在JavaScript) – CodingIntrigue

回答

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') 
 
}

+0

有人說它已經發生....兩次:p –