JavaScript Try...Catch 語句
try...catch 的作用是測試代碼中的錯(cuò)誤。
實(shí)例
- try...catch 語句
- 如何編寫 try...catch 語句。
- 帶有確認(rèn)框的 try...catch 語句
- 另一個(gè)編寫 try...catch 語句的例子。
JavaScript - 捕獲錯(cuò)誤
當(dāng)我們在網(wǎng)上沖浪時(shí),總會(huì)看到帶有 runtime 錯(cuò)誤的 Javascript 警告框,同時(shí)會(huì)詢問我們“是否進(jìn)行 debug?”。像這樣的錯(cuò)誤信息或許對開發(fā)人員有用,對用戶則未必。當(dāng)錯(cuò)誤發(fā)生時(shí),他們往往會(huì)選擇離開這個(gè)站點(diǎn)。
本節(jié)向你講解如何捕獲和處理 Javascript 的錯(cuò)誤消息,這樣就可以為受眾提供更多的便利。
有兩種在網(wǎng)頁中捕獲錯(cuò)誤的方法:
- 使用 try...catch 語句。(在 IE5+、Mozilla 1.0、和 Netscape 6 中可用)
- 使用 onerror 事件。這是用于捕獲錯(cuò)誤的老式方法。(Netscape 3 以后的版本可用)
注意:chrome、opera 和 safari 瀏覽器不支持 onerror 事件。
Try...Catch 語句
try...catch 可以測試代碼中的錯(cuò)誤。try 部分包含需要運(yùn)行的代碼,而 catch 部分包含錯(cuò)誤發(fā)生時(shí)運(yùn)行的代碼。
語法:
try
{ //在此運(yùn)行代碼 }catch(err)
{ //在此處理錯(cuò)誤 }
注意:try...catch 使用小寫字母。大寫字母會(huì)出錯(cuò)。
實(shí)例 1
下面的例子原本用在用戶點(diǎn)擊按鈕時(shí)顯示 "Welcome guest!" 這個(gè)消息。不過 message() 函數(shù)中的 alert() 被誤寫為 adddlert()。這時(shí)錯(cuò)誤發(fā)生了:
<html> <head> <script type="text/javascript"> function message() { adddlert("Welcome guest!") } </script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html>
我們可以添加 try...catch 語句,這樣當(dāng)錯(cuò)誤發(fā)生時(shí)可以采取更適當(dāng)?shù)拇胧?/p>
下面的例子用 try...catch 語句重新修改了腳本。由于誤寫了 alert(),所以錯(cuò)誤發(fā)生了。不過這一次,catch 部分捕獲到了錯(cuò)誤,并用一段準(zhǔn)備好的代碼來處理這個(gè)錯(cuò)誤。這段代碼會(huì)顯示一個(gè)自定義的出錯(cuò)信息來告知用戶所發(fā)生的事情。
<html> <head> <script type="text/javascript"> var txt="" function message() {try
{ adddlert("Welcome guest!") }catch(err)
{ txt="此頁面存在一個(gè)錯(cuò)誤。\n\n" txt+="錯(cuò)誤描述: " + err.description + "\n\n" txt+="點(diǎn)擊OK繼續(xù)。\n\n" alert(txt) } } </script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html>
實(shí)例 2
下一個(gè)例子會(huì)顯示一個(gè)確認(rèn)框,讓用戶來選擇在發(fā)生錯(cuò)誤時(shí)點(diǎn)擊確定按鈕來繼續(xù)瀏覽網(wǎng)頁,還是點(diǎn)擊取消按鈕來回到首頁。如果 confirm 方法的返回值為 false,代碼會(huì)把用戶重定向到其他的頁面。如果 confirm 方法的返回值為 true,那么代碼什么也不會(huì)做。
<html> <head> <script type="text/javascript"> var txt="" function message() {try
{ adddlert("Welcome guest!") }catch(err)
{ txt="There was an error on this page.\n\n" txt+="Click OK to continue viewing this page,\n" txt+="or Cancel to return to the home page.\n\n" if(!confirm(txt)) { document.location.href="http://chabaoo.cn/" } } } </script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html>
onerror 事件
我們馬上會(huì)講解 onerror 事件。但首先您需要學(xué)習(xí)如何使用 throw 語句來創(chuàng)建異常。throw 語句可以與 try...catch 語句一起使用。