乖,別哭的薄殼
          ~一份耕耘,一份收獲~
          posts - 23,comments - 260,trackbacks - 0

          1.onerror事件處理函數
          onerror事件處理函數是第一個用來協助javascript處理錯誤的機制。頁面上出現異常時,error事件便在window對象上觸發。
          例如:

          <html>
              
          <head>
                  
          <title>OnError Example</title>
                  
          <script type="text/javascript">
                      window.onerror 
          = function () {
                          alert(
          "An error occurred.");
                      }
                  
          </script>
              
          </head>
              
          <body onload="nonExistentFunction()">
              
          </body>
          </html>
          在這個例子中,嘗試調用不存在的函數nonExistentFunction()時,就會引發一個異常。這時會彈出警告框顯示“An error occurred.”不幸的是,瀏覽器的錯誤信息也顯示出來了,要從瀏覽器中隱藏它,onerror事件處理函數必須返回true值:如下
          <html>
              
          <head>
                  
          <title>OnError Example</title>
                  
          <script type="text/javascript">
                      window.onerror 
          = function () {
                          alert(
          "An error occurred.");
                          
          return true;
                      }
                  
          </script>
              
          </head>
              
          <body onload="nonExistentFunction()">
              
          </body>
          </html>

          2.取出錯誤信息
          onerror事件處理函數提供了三種信息來確定錯誤確切的性質:
          錯誤信息--對于給定錯誤,瀏覽器會顯示同樣的信息。
          URL--在哪個文件中發生了錯誤。
          行號--給定的URL中發生錯誤的行號。
          <html>
              
          <head>
                  
          <title>OnError Example</title>
                  
          <script type="text/javascript">
                      window.onerror 
          = function (sMessage, sUrl, sLine) {
                          alert(
          "An error occurred:\n" + sMessage + "\nURL: " + sUrl + "\nLine Number: " + sLine);
                          
          return true;
                      }
                  
          </script>
              
          </head>
              
          <body onload="nonExistentFunction()">
              
          </body>
          </html>

          3.圖像載入錯誤
          圖像對象也支持onerror事件處理函數。當一個圖像由于某種原因未能成功載入時(例如,文件不存在),error事件便在這個圖像上觸發。
          <html>
              
          <head>
                  
          <title>Image Error Test</title>
              
          </head>
              
          <body>
                  
          <p>The image below attempts to load a file that doesn't exist.</p>
                  
          <img src="blue.gif" onerror="alert('An error occurred loading the image.')" />
              
          </body>
          </html>

          與window對象的onerror事件處理函數不同,image的onerror事件處理函數沒有任務關于額外信息的參數。

          4.處理語法錯誤
          onerror事件處理函數不僅可以處理異常,它還能處理語法錯誤,也只有它才能處理。
          <html>
              
          <head>
                  
          <title>OnError Example</title>
                  
          <script type="text/javascript">
                      window.onerror 
          = function (sMessage, sUrl, sLine) {
                          alert(
          "An error occurred:\n" + sMessage + "\nURL: " + sUrl + "\nLine Number: " + sLine);
                          
          return true;
                      }
                      alert(
          "Syntax error.";
                  
          </script>
              
          </head>
              
          <body onload="nonExistentFunction()">
                  
          <p>The syntax error on this page comes <em>after</em> the <code>onerror</code>
                  event handler is defined, so the custom dialog catches it.
          </p>
                  
          <p><strong>Note:</strong> This may not work in newer browsers with tighter security restrictions.</p>
              
          </body>
          </html>

          注:使用onerror事件處理函數的主要問題是,它是BOM的一部分,所以,沒有任何標準能控制它的行為。因此,不同的瀏覽器使用這個事件處理函數處理錯誤的方式有明顯的不同。例如,在IE中發生error事件時,正常的代碼會繼續執行:所有的變量和數據都保存下來,并可能過onerror事件處理函數訪問。然而在Mozilla中,正常的代碼執行都會結束,同時所有錯誤發生之前的變量和數據都被銷毀。Safari和Konqueror不支持window對象上的onerror事件處理函數,但是它們支持圖像上的onerror事件處理函數。

          5.try...catch語句
          <html>
              
          <head>
                  
          <title>Try Catch Example</title>
                  
          <script type="text/javascript">
                          
          try {
                              window.nonExistentFunction();
                              alert(
          "Method completed.");
                          } 
          catch (exception) {
                              alert(
          "An exception occurred.");
                          } 
          finally {
                              alert(
          "End of try...catch test.");
                          }
                  
          </script>
              
          </head>
              
          <body>
              
          </body>
          </html>

          與java不同,ECMAScript標準在try...catch語句中指定只能有一個catch子句。因為javascript是弱類型,沒辦法指明catch子句中的異常的特定類型。不管錯誤是什么類型,都由同一個catch子句處理。Mozilla對其進行了擴展,可為try...catch語句添加多個catch子句。當然只有Mozilla才能使用這個形式,所以不推薦使用。

          (1)嵌套try...catch語句
          <html>
              
          <head>
                  
          <title>Try Catch Example</title>
                  
          <script type="text/javascript">
                          
          try {
                              eval(
          "a ++ b");        //causes error
                          } catch (oException) {
                              alert(
          "An exception occurred.");
                              
          try {
                                  
          var arrErrors = new Array(10000000000000000000000);  //causes error
                                  arrErrors.push(exception);
                              } 
          catch (oException2) {
                                  alert(
          "Another exception occurred.");
                              }
                          } 
          finally {
                              alert(
          "All done.");
                          }

                  
          </script>
              
          </head>
              
          <body>
              
          </body>
          </html>
          (2)Error對象
          類似于java有個用于拋出的基類Exception,javascript有個Error基類用于拋出。Error對象有以下特性:
          name--表示錯誤類型的字符串。
          message--實際的錯誤信息。
          Error對象的名稱對象對應于它的類(因為Error只是一個基類),可以是以下值之一:
          發生原因
          EvalError 錯誤發生在eval()函數中
          RangeError 數字的值超出javascript可表示的范圍
          ReferenceError 使用了非法的引用
          SyntaxError 在eval()函數調用中發生了語法錯誤。其他的語法錯誤由瀏覽器報告,無法通過try...catch語句處理
          TypeError 變量的類型不是預期所需的
          URIError 在encodeURI()或者decodeURI()函數中發生了錯誤

          Mozilla和IE都擴展了Erro對象以適應各自的需求。Mozilla提供一個fileName特性來表示錯誤發生在哪一個文件中,以及一個stack特性以包含到錯誤發生時的調用堆棧;IE提供了一個number特性來表示錯誤代號。
          (3)判斷錯誤類型
          <html>
              
          <head>
                  
          <title>Try Catch Example</title>
                  
          <script type="text/javascript">
                          
          try {
                              eval(
          "a ++ b");        //causes SyntaxError
                          } catch (oException) {
                              
          if (oException.name == "SyntaxError") {      //或者if(oException instanceof SyntaxError)
                                  alert(
          "Syntax Error: " + oException.message);
                              } 
          else {
                                  alert(
          "An unexpected error occurred: " + oException.message);
                              }
                          }

                  
          </script>
              
          </head>
              
          <body>
              
          </body>
          </html>

          (4)拋出異常
          ECMAScript第三版還引入了throw語句,用于有目的的拋出異常。語法如下:
          throw error_object;      //error_object可以是字符串、數字、布爾值或者是實際的對象。
          <html>
              
          <head>
                  
          <title>Try Catch Example</title>
                  
          <script type="text/javascript">
                          
          function addTwoNumbers(a, b) {
                              
          if (arguments.length < 2) {
                                  
          throw new Error("Two numbers are required.");
                              } 
          else {
                                  
          return a + b;
                              }
                          }
                          
                          
          try {
                              result 
          = addTwoNumbers(90);
                          } 
          catch (oException) {
                              alert(oException.message);      
          //outputs "Two numbers are required."
                          }

                  
          </script>
              
          </head>
              
          <body>
              
          </body>
          </html>

          另個,因為瀏覽器不生成Error對象(它總是生成一個較精確的Error對象,比如RangeError),所以區分瀏覽器拋出的錯誤和開發人員拋出的錯誤很簡單,使用前面的技術就行了:
          try{
             result = addTwoNumber(90,parseInt(z));
          }catch(oException){
             if(oException instanceof SyntaxError){
                alert("Syntax Error: "+oException.message);
             }else if(oException instanceof Error){
                alert(oException.message);
             }
          }
          注意檢查instanceof Error必須是if語句中的最后一個條件,因為所有其他的錯誤類都繼承于它(所以在檢測instanceof Error時都返回true)。

          所有的瀏覽器都可以報告開發人員拋出的錯誤,但是錯誤消息的顯示方式可能有所不同。IE6只會在拋出Error對象時,才顯示錯誤信息;其他情況下,它就只顯示Exception thrown and not caught,而沒有任何詳細內容。Mozilla則會報告Error:uncaught exception:然后調用所拋出的對象的toString()方法。
          posted on 2007-04-25 00:58 小祝 閱讀(2093) 評論(1)  編輯  收藏 所屬分類: Javascript

          FeedBack:
          # re: javascript學習筆記(八)--錯誤處理
          2007-04-26 11:31 | 睿不可當
          還能說什么呢???
          頂了!  回復  更多評論
            
          主站蜘蛛池模板: 麦盖提县| 饶阳县| 常宁市| 哈巴河县| 涞水县| 织金县| 铁力市| 灌阳县| 古田县| 汕尾市| 丰台区| 嘉善县| 莱州市| 钦州市| 泸定县| 都江堰市| 临夏县| 壤塘县| 亚东县| 上林县| 营山县| 乐平市| 阿荣旗| 宜川县| 分宜县| 沁源县| 泸水县| 塔河县| 西盟| 卢氏县| 峨山| 阳信县| 新和县| 兴山县| 射洪县| 准格尔旗| 双柏县| 治多县| 寿光市| 常宁市| 潮安县|