2013-03-26 43 views
2

我試圖找出爲什麼我的代碼不會引發並顯示錯誤消息(頁只是空白)後,我把它用下面的語句:JavaScript異常不工作

文件撰寫(添加(10,wrong_input));

program.js

var add = function (a,b){ 
    if(typeof a !== 'number' || typeof b !== 'number'){ 
     throw{ 
      name: 'TypeError', 
      message: 'add needs numbers' 
     } catch(e){ 
      document.writeln(e.name + ': ' + e.message); 
     } 
    } 
    return a + b; 
} 

program.html

+1

您要查找錯誤信息的位置? – Quentin 2013-03-26 20:23:09

+9

你在混合投擲並嘗試。 – bfavaretto 2013-03-26 20:23:28

+0

我在找它可以在瀏覽器中顯示 – Anthony 2013-03-26 20:23:42

回答

6

throw聲明沒有catch條款,try一樣。你應該分開扔扔。例如:

var add = function (a,b){ 
    if(typeof a !== 'number' || typeof b !== 'number'){ 
     throw{ 
      name: 'TypeError', 
      message: 'add needs numbers' 
     } 
    } 
    return a + b; 
} 

try { 
    add('foo', 1); 
} catch(ex) { 
    alert(ex.message); 
} 

請注意,我用alert更換document.writeln,因爲如果頁面加載後運行前將覆蓋整個文件。如果你想要更好看的東西,直接操作DOM(通過改變某個元素的innerHTML,附加節點等)。

+0

+1謝謝你的幫助 – Anthony 2013-03-26 22:27:55

2

您的錯誤處理代碼稍微關閉,您不能拋出錯誤,然後嘗試寫出它。你要麼做:

if(typeof a !== 'number' || typeof b !== 'number'){ 
    document.write("TypeError" + ": " + "add needs numbers"); 
} 

或者只是簡單地throw它:

if(typeof a !== 'number' || typeof b !== 'number'){ 
    throw { 
     message: "add needs numbers", 
     name: "TypeError" 
    } 
} 

然後做你try catch在你的函數調用。但我個人認爲,堅持第一。

+0

+1非常有用的評論,謝謝 – Anthony 2013-03-26 22:28:14

1

AS評論bfaretto,你是混合投擲和嘗試。

拋出拋出一個你定義的異常,但你使用它作爲try..catch塊。這裏是你如何使用throw和try..catch在一起。

var add = function (a,b){ 
    try { 
     if(typeof a !== 'number' || typeof b !== 'number'){ 
      var n = { 
       name: 'TypeError', 
       message: 'add needs numbers' 
      }; 
      throw n; 
     } 
     // throws an exception with a numeric value 
    } catch (e) { 
     console.log(e.name); 
    } 
} 
+0

+1非常感謝 – Anthony 2013-03-26 22:28:38