JavaScript » Statements » try...catch

try {statements1} [catch (exception){statements2}]

The try...catch statement is used to test a block of code for errors. The try block contains the code to be run, while the catch block contains the code to execute if there is an error. The exception argument is a variable in which to store the error, in this case it is the variable er.


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.