2011-12-16 38 views
0

所以在我的應用程序發生特定情況時,我想顯示一個警報,然後停止程序執行。我在某處讀到這可以用throw()完成,但我無法完成這項工作。在錯誤情況下停止JavaScript程序操作?

這是我已經試過:

function check_for_error(data) { 
    try { 
     if (<error condition>) { 
      throw "error"; 
     } 
    } catch(e) { 
      alert('error occured'); 
       // I want program execution to halt here but it does not, 
       // it continues within the calling code 
    } 
} 
+0

您可以嘗試從catch塊中拋出錯誤,然後在callee方法中處理它。基本上退出。 – Sid 2011-12-16 19:10:45

回答

1

必須重新拋出異常:

... 
catch(e) { 
    alert('error occurred'); 
    throw(e); 
} 
+0

謝謝,但這給了我一個'未捕獲的異常'錯誤。 – bethesdaboys 2011-12-16 21:37:59

2

你應該在catch塊中拋出另一個錯誤。或者根本不抓住最初的錯誤。

目前,發生以下情況:

<error condition me> 
throw "error" 
catch error and Show alert 

要 「叫停」 的執行,你必須提醒後添加throw e(在catch塊):

catch(e) { 
    alert('error occurred'); 
    throw e; 
} 

如果你的功能從另一個try-catch塊中調用,你還必須對該塊應用類似的機制。

0

,你也可以

function check_for_error(data) { 
    try { 
     //WHEN ERROR OCCURES 
    } catch(e) { 
      alert('error occured'); 
       // I want program execution to halt here but it does not, 
       // it continues within the calling code 
      throw(e); 
      return; 
    } 
} 
0

擲纔會停止同步rutines的執行,例如,如果你做一個異步HTTP請求時,它會執行回調函數而不管以前的錯誤。從w3c

投擲DOC:

語法

拋出異常

例外可以是一個字符串,整數,布爾值或對象。

相關問題