W3Schools.com

JavaScript Throw Statement


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, lower than 0, or not a number, we are going to throw an error. The error is then caught by the catch argument and the proper error message is displayed:

Example

<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 5 and 10:","");
try
  {
  if(x>10)
    {
    throw "Err1";
    }
  else if(x<5)
    {
    throw "Err2";
    }
  else if(isNaN(x))
    {
    throw "Err3";
    }
  }
catch(err)
  {
  if(err=="Err1")
    {
    document.write("Error! The value is too high.");
    }
  if(err=="Err2")
    {
    document.write("Error! The value is too low.");
    }
  if(err=="Err3")
    {
    document.write("Error! The value is not a number.");
    }
  }
</script>
</body>
</html>

Try it yourself »


WEB HOSTING
Best Web Hosting
PHP MySQL Hosting
Best Hosting Coupons
UK Reseller Hosting
Cloud Hosting
Top Web Hosting
$7.95/mo SEO Hosting
Premium Website Design
WEB BUILDING
XML Editor - Free Trial!
FREE Website BUILDER
Free Website Templates Free CSS Templates
Make Your Own Website
W3SCHOOLS EXAMS
Get Certified in:
HTML, CSS, JavaScript, XML, PHP, and ASP
W3SCHOOLS BOOKS
New Books:
HTML, CSS
JavaScript, and Ajax
STATISTICS
Browser Statistics
Browser OS
Browser Display
SHARE THIS PAGE