2010-08-14 30 views
5

我想在browsermob中測試某些輸入字段是否工作。我試圖使用我以前從未使用過的try ... catch語句。我知道表單是:JavaScript的嘗試... catch語句的工作方式

try { 
//some code 
} catch(){ 
//some error code 
}; 

究竟應該在catch語句之後的圓括號裏放什麼? 當我嘗試使用該語句時,它會通過catch語句運行所有內容,而不管它是否爲錯誤。我究竟做錯了什麼?

回答

9

查看try...catch statement」 guide on MDN

簡而言之,try/catch用於處理異常(使用throw語句「拋出」)。對於try/catch語句的語法是:

try { 
    // Code 
} catch (varName) {    // Optional 
    // If exception thrown in try block, 
    // execute this block 
} finally {      // Optional 
    // Execute this block after 
    // try or after catch clause 
    // (i.e. this is *always* called) 
} 

varName只提供給了catch塊的範圍。它引用拋出的異常對象(可以是任何類型的對象,例如String,但通常是Error object)。

+0

謝謝,我覺得這是現在做更有意義。那麼catch之後的括號是否包含錯誤的變量? – chromedude 2010-08-14 18:07:04

+0

@srmorriso,是;看我的編輯。 – strager 2010-08-14 18:09:26

+0

好的,謝謝。現在有意義 – chromedude 2010-08-14 18:14:21

3

try catch語句用於檢測在try -block內引發的異常/錯誤。在catch塊中,您可以對這種異常行爲做出反應並嘗試解決它或進入安全狀態。

你有差不多吧聲明:

try { 
// code that may fail with error/exception 
} catch (e) { // e represents the exception/error object 
// react 
} 

請看下面的例子:

try { 
    var x = parseInt("xxx"); 
    if(isNaN(x)){ 
    throw new Error("Not a number"); 
    } 
} catch (e) { // e represents the exception/error object 
alert(e); 
} 

try { 
// some code 
if(!condition){ 
    throw new Error("Something went wrong!"); 
} 
} catch (e) { // e represents the exception/error object 
alert(e); 
} 
+0

所以你不一定需要有最​​後的聲明? – chromedude 2010-08-14 18:15:28

+0

yes終於是聲明的一個可選部分,它保證它內部的代碼被執行,無論是否存在異常。 – 2010-08-20 11:58:05

1

內嘗試{...}的東西是要執行什麼。 catch(){...}中的東西是你想要執行的,如果你從try {...}中執行的任何東西得到任何javascript錯誤0127 try {...}塊中的javascript錯誤。你可以找出錯誤是由例如這樣的:

try { 
// do something 
} catch (err) { 
    alert(err); 
} 
+0

謝謝,這就是我正在試圖找出 – chromedude 2010-08-14 18:12:27

0

很可能拋出一個異常,進入try { }代碼,當有異常拋出要運行的代碼,進入catch() { }。在catch()中,您可以指定要捕獲哪些異常,以及在哪個自動變量中放置它。無論是否拋出異常,總是運行 finally { }

1

ECMAScript規格,

try { 
    // Code 
} catch (varName) { // optional if 'finally' block is present. 
    if (condition) { // eg. (varName instanceof URIError) 
    // Condition (Type) specific error handling 
    } 
    else { 
    // Generic error handling 
    } 
} finally {   // Optional if 'catch' block is present. 
    // Execute this block after 
    // try or after catch clause 
    // (i.e. this is *always* called) 
}