JavaScript Errors – Throw and Try to Catch

來源:互聯網
上載者:User

The try statement lets you test a block of code  for errors.

The catch statement lets you handle the error.

The throw statement lets you create custom  errors.

 Errors Will Happen!

When the JavaScript engine is executing JavaScript code, different errors can  occur:

It can be syntax errors, typically coding errors or typos made by the  programmer.

It can be misspelled or missing features in the language (maybe due to  browser differences).

It can be errors due to wrong input, from a user, or from an Internet server.

And, of course, it can be many other unforeseeable things.

JavaScript Throws Errors

When an error occurs, when something goes wrong, the JavaScript engine will  normally stop, and generate an error message.

The technical term for this is: JavaScript will throw an  error.

JavaScript try and catch

The try statement allows you to define a block of code to be  tested for errors while it is being executed.

The catch statement allows you to define a block of code to  be executed, if an error occurs in the try block.

The JavaScript statements try and catch come in pairs.

Syntax
try   {   //Run some code here   } catch(err)   {   //Handle errors here   }
The Throw Statement

The throw statement allows you to create a custom error.

The correct technical term is to create or throw an exception.

If you use the throw statement together with try and catch, you can control program  flow and generate custom error messages.

Syntaxthrow exception

The exception can be a JavaScript String, a Number, a Boolean or an Object.

Example

This example examines the value of an input variable. If the value is wrong,  an exception (error) is thrown. The error is caught by the catch statement and a custom error message is displayed:

Example
<script>function myFunction(){try  {   var x=document.getElementById("demo").value;  if(x=="")    throw "empty";  if(isNaN(x)) throw "not a number";  if(x>10)     throw "too high";  if(x<5)      throw "too low";  }catch(err)  {  var y=document.getElementById("mess");  y.innerHTML="Error: " + err + ".";  }}</script><h1>My First JavaScript</h1><p>Please input a number between 5 and 10:</p><input id="demo" type="text"><button type="button" onclick="myFunction()">Test Input</button><p id="mess"></p>

 

相關文章

聯繫我們

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