throw to display error message in JavaScript program
We can use throw to pass some error conditions and monitor the program flow within a script. You can see how try catch is used to manage error handling at various stages of a program. The error message or any fixed message can be generated under different condition and can be collected by using catch.
Here is an example of throw command used under two different conditions. You can change the value of variable my_sum and see the difference in error messages.
<script type="text/javascript">
<!--
try
{
var my_sum=5;
document.write("The sum of 2 and 3 = " + my_sum);
if(my_sum != 5 )
throw "error1";
else if (my_sum==5)
throw "error2";
}
catch(err)
{
if(err=="error1")
document.write("<br>Sum of 2 and 3 has to be equal to 5");
else if(err=="error2")
document.write("<br>Correct the Sum of 2 and 3 has to be equal to 5");
else
document.write("There is some different error");
}
//-->
</script>