JavaScript Throw Statement

previous next


The throw statement allows you to create an exception.


The Throw Statement

The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages.

Syntax

throw(exception)

The exception can be a string, integer, Boolean or an object.

Note that throw is written in lowercase letters. Using uppercase letters will generate a JavaScript error!

Example

The example below determines the value of a variable called x. If the value of x is higher than 10 or lower than 0 we are going to throw an error. The error is then caught by the catch argument and the proper error message is displayed:

<html>
<body>

<script type="text/javascript">
var x=prompt("Enter a number between 0 and 10:","")
try
{
  if
(x>10) throw "High"
  if(x<0 ) throw "Low"
  document.write("Your number is: " + x)
}
catch
(exp)
{
  if
(exp=="High") alert("Error! The value is too high")
  if(exp== "Low") alert("Error! The value is too low")
  document.write("The value of the thrown error is: " + exp)
}
</script>

</body>
</html>

 


Try it

To see how HTML and JavaScript work, you can only push the submit button, or you can make your own HTML and JavaScript code.

           

 


previous next