Use of Throw Statement in JavaScript

In this article I have described about error handling in JavaScript with Throw statement.
  • 1899

Throw Statement in JavaScript

The Throw is a user defined exception which allow us to create an exception. We can use this statement to generate appropriate error message and also to control the flow of program.

Syntax

throw exception  

Example

<html><title>Throw Statement in JavaScript</title>

<body>

<script type="text/javascript">

var a=prompt("Chose any number between 1 and 100 :","");

try

{

     if(a>50)

     {

          throw "er1";

     }

     else if(a<50)

     {

          throw "er2";

     }

     else if(isNaN(x))

     {

          throw "er3";

     }

}

catch(err)

{

     if(err=="er1")

      {

            document.write("Error! Number is greaterthan 50.");

      }

      if(err=="er2")

      {

            document.write("Error! Number is  less than 50");

      }

      if(err=="er3")

      {

            document.write("Error! In can't be determine as number");

      }

}

</script>

</body>

</html>

Output

When we run this program then

thrw1.jpg

When we some value in Text Box then

thrw2.jpg

Further Readings

You may also want to read these related articles :

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2020 DotNetHeaven. All rights reserved.