javascript 中的異常處理

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.