JavaScript Try Catch 執行個體教程

來源:互聯網
上載者:User

JavaScript Try Catch 在js裡面是用來捕捉錯誤的,下在我們來看看try catch   的執行個體與教程嘍.

其中的try ... catch聲明允許你測試一個代碼塊的錯誤。


範例
其中的try ... catch聲明
如何撰寫一個try ... catch聲明。

<script type="text/javascript">
var txt="";
function message()
{
try
  {
  adddlert("Welcome guest!");
  }
catch(err)
  {
  txt="There was an error on this page.nn";
  txt+="Error description: " + err.description + "nn";
  txt+="Click OK to continue.nn";
  alert(txt);
  }
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()" />
</body>

其中的try ... catch聲明的確認框
另一個例子是如何寫一個try ... catch聲明。

<script type="text/javascript">
var txt=""
function message()
{
try
  {
  adddlert("Welcome guest!");
  }
catch(err)
  {
  txt="There was an error on this page.nn";
  txt+="Click OK to continue viewing this page,n";
  txt+="or Cancel to return to the home page.nn";
  if(!confirm(txt))
    {
    document.location.href="http://www.111cn.net/";
    }
  }
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()" />
</body>

JavaScript的-追趕錯誤
當瀏覽網頁在互連網上,我們都已經看到一個JavaScript警告框告訴我們有一個執行階段錯誤,並要求: “你想要偵錯嗎? ” 。錯誤訊息這樣可能是有用的開發而不是使用者。當使用者看到的錯誤,他們往往離開網頁。

本章將教你如何捕獲和處理JavaScript的錯誤訊息,所以你不要失去你的聽眾。

有兩種方式追趕中的錯誤網頁:

通過使用嘗試... catch語句(適用於IE5 + , Mozilla的1.0和Netscape 6 )
通過使用onerror事件。這是舊標準的解決方案時發現錯誤(www.111cn.net  )



嘗試... catch語句
其中的try ... catch聲明允許你測試一個代碼塊的錯誤。 try塊包含的代碼運行,並catch塊中包含的代碼將被處決,如果發生錯誤。

文法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.