在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文網站有這方面的資料。