JavaScript » Statements » throw

throw (exception)

The throw statement allows the programmer to create an exception. This exception can be a string, integer, Boolean or an object. Coupling the throw statement with the try...catch statement, the programmer can control program flow and generate accurate error messages.


try {
   if(z == 1)
      throw "Error 1"
   else if(z == 2)
      throw "Error 2"
catch(er) {
   if(er == "Error 1")
      alert("Error 1 Please contact system Administrator")
   if(er == "Error 2")
      alert("Error 2 Please Reload the page")

This example determines the value of variable(z), and generates an error accordingly. This error is then caught by the catch argument and the proper error message is then displayed.