javascript中try catch finally 的使用
來源:互聯網
上載者:User
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