javascript中try catch finally 的使用
try...catch...finally 語句
為 JScript 實現錯誤處理。
try {
tryStatements}
catch(exception){
catchStatements}
finally {
finallyStatements}
=============
參數
tryStatement
必選項。可能發生錯誤的語句。
exception
必選項。任何變數名。exception 的初始化值是扔出的錯誤的值。
catchStatement
可選項。處理在相關聯的 tryStatement 中發生的錯誤的語句。
finallyStatements
可選項。在所有其他過程發生之後無條件執行的語句。
說明
try...catch...finally 語句提供了一種方法來處理可能發生在給定代碼塊中的某些或全部錯誤,同時仍保持代碼的運行。如果發生了程式員沒有處理的錯誤,JScript 只給使用者提供它的普通錯誤資訊,就好象沒有錯誤處理一樣。
tryStatements 參數包含可能發生錯誤的代碼,而 catchStatement 則包含處理任何發生了的錯誤的代碼。如果在 tryStatements 中發生了一個錯誤,則程式控制被傳給 catchStatements 來處理。exception 的初始化值是發生在 tryStatements 中的錯誤的值。如果錯誤不發生,則不執行 catchStatements。
如果在與發生錯誤的 tryStatements 相關聯的 catchStatements 中不能處理該錯誤,則使用 throw 語句來傳播、或重新扔出這個錯誤給更進階的錯誤處理程式。
在執行完 tryStatements 中的語句,並在 catchStatements 的所有錯誤處理發生之後,可無條件執行 finallyStatements 中的語句。
請注意,即使在 try 或 catch 塊中返回一個語句,或在 catch 塊重新扔出一個錯誤,仍然會執行 finallyStatements 編碼。一般將確保 finallyStatments 的運行,除非存在未處理的錯誤。(例如,在 catch 塊中發生執行階段錯誤。)。
樣本
下面的例子闡明了JScript 特例處理是如何進行的。
try {
print("Outer try running..");
try {
print("Nested try running...");
throw "an error";
}
catch(e) {
print("Nested catch caught " + e);
throw e + " re-thrown";
}
finally {
print("Nested finally is running...");
}
}
catch(e) {
print("Outer catch caught " + e);
}
finally {
print("Outer finally running");
}
// Windows Script Host 作出該修改從而得出 WScript.Echo(s)
function print(s){
document.write(s);
}
將得出以下結果:
Outer try running..
Nested try running...
Nested catch caught an error
Nested finally is running...
Outer catch caught an error re-thrown
Outer finally running
如下是Javascript的例外處理的一個執行個體。
var array = null;
try {
document.write(array[0]);
} catch(err) {
document.writeln("Error name: " + err.name + "");
document.writeln("Error message: " + err.message);
}
finally{
alert("object is null");
}
程式執行過程
1. array[0]的時候由於沒有建立array數組,array是個Null 物件,程式中調用array[0]就會產生object is null的異常
2. catch(err)語句捕獲到這個異常通過err.name列印了錯誤類型,err.message列印了錯誤的詳細資料.
3. finally類似於java的finally,無論有無異常都會執行.
現總結Error.name的六種值對應的資訊:
1. EvalError:eval()的使用與定義不一致
2. RangeError:數值越界
3. ReferenceError:非法或不能識別的引用數值
4. SyntaxError:發生文法解析錯誤
5. TypeError:運算元類型錯誤
6. URIError:URI處理函數使用不當