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