乖,别哭的薄壳
~一份耕耘,一份收获~
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 小祝 阅读(2076) 评论(1)  编辑  收藏 所属分类: Javascript

FeedBack:
# re: javascript学习笔记(八)--错误处理
2007-04-26 11:31 | 睿不可当
还能说什么呢!?
顶了!  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: