Hosting Solutions
mobile_logo Table of Contents
seal_frontseal_back

try catch

try...catch statements are used to execute code, and catch any subsequent errors that might exist in that code. The catch statement will catch the error so that it can be handled.

Syntaxtry { ... } catch( error ) { ... }
There are actually four statements that may be involved with a try...catch statement.
  • try
  • catch
  • throw
  • finally
try{ doSomething(); } catch(error){ document.write(error); // ReferenceError: doSomething is not defined }

Running the code above we get a Reference Error exception thrown when trying to run the doSomething() function because that function has not been defined in our document. Write a function called doSomething() above that code in order to see the function run when you "try" it and the error catch will be bypassed.

finally

The finally statement is used to run code unconditionally after try...catch statements.

function func1(){ document.write("<br>func1 called to run"); } try{ func2(); } catch(error){ document.write(error); } finally { func1(); }

throw

The throw statement is used to throw a user-defined error message to a catch statement.

function myObject(){ this.x = 40; } var obj = new myObject(); try{ if(obj.x < 50){ throw "Program failed because x is less than 50."; } else { document.write("Program can continue with x value of 50 or greater"); } } catch(error){ document.write(error); }

JavaScript

Statements

breakconstcontinuedo whileforfor inif elselabelreturnswitchtry catchvarwhilewith