javascript中 try catch finally 的使用


例一:
function
message(){   try   {     adddlert("Welcome guest!")   }   catch(err)   {     txt="此頁面存在一個錯誤。\n\n"      txt+="錯誤描述: " + err.description + "\n\n"      txt+="點擊OK繼續。\n\n"     alert(txt)   } }
例二:
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是個空對象,程序中調用array[0]就會產生object is null的異常 
2. catch(err)語句捕獲到這個異常通過err.name打印了錯誤類型,err.message打印了錯誤的詳細信息. 
3. finally類似於java的finally,無論有無異常都會執行.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM