javascript 中的异常处理

在javascript中也可以像java、C#等语言那样用try、catch、finally来作异常处理的(IE5.0以后支持),废话少讲,下面来个例子:

<script language="javascript">

function test()
{
    
try
    {
        CreateException();
    }
    
catch(ex)//catch the ex
    {
            alert(ex.number
+"\n"+ex.description);
    }
    
finally
    {
        alert(
"end");//do something finally
    }
}
</script>

这个例子运行一个未定义的函数CreateException(),捕捉到的ex有以下属性:number和description。
那么要抛出自己的异常怎么做呢?
再看个例子:

<script language="javascript">

function initException(Num,Msg)//define an Exception
{
    
this.ErrorNumber=Num;//error's number
    this.ErrorMessage=Msg;//error's message
}
function CreateException()
{
    ex
=new initException(1,"Created!");//create the excepion
    throw ex;//throw ex
}
function test()
{
    
try
    {
        CreateException();
    }
    
catch(ex)//catch the ex
    {
        
if(ex instanceof initException)//if the exception is our target,do something
        {
            alert(ex.ErrorNumber
+ex.ErrorMessage);
        }
        
else//else throw again
        {
            
throw ex;
        }
    }
    
finally
    {
        alert(
"end");//do something finally
    }
}
</script>


这个例子是抛出自己的异常,而自己抛出的异常的属性则可以自己定义多个,catch到异常之后还可以用instanceof来判断异常类型,这在有很多个异常的时候很有用。和java、C#等语言用多个catch块来捕捉不同的异常作对比,javascript只能有一个catch块,则可以用instanceof来区分不同的异常。

较早版本的javascript(1.3以前?)是用window.onerror事件来处理异常的,例子:

<script language="javascript">
function CreateException()
{
    ERROR();
//cause an error
}

function handleError()
{
    
return true;
}
window.onerror
=handleError;
</script>

例子中如果执行CreateException()的话,由于ERROR()是未定义的,引发异常,通过handleError()函数处理。

参考资料:
通过Google可以找到很多E文网站有这方面的资料。

posted @ 2005-01-12 14:34  epan  阅读(1698)  评论(2编辑  收藏  举报