Jquery中try catch finally的使用
例一: function message(){ try { adddlert("Welcome guest!") } catch(err) { txt="此頁面存在一個錯誤。\n\n" txt ="錯誤描述: " err.description "\n\n" txt ="點擊OK繼續(xù)。\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"); }
程序執(zhí)行過程
1. array[0]的時候由于沒有創(chuàng)建array數(shù)組,array是個空對象,程序中調(diào)用array[0]就會產(chǎn)生object is null的異常
2. catch(err)語句捕獲到這個異常通過err.name打印了錯誤類型,err.message打印了錯誤的詳細信息.
3. finally類似于java的finally,無論有無異常都會執(zhí)行.
原文鏈接:Jquery中try catch finally的使用