Home Videos Exercises MCQ Q&A Quiz E-Store Services Blog Sign in Appointment Payment

JavaScript Error handling

JavaScript is a loosely-typed language. It does not give compile-time errors. So some times you will get a runtime error for accessing an undefined variable or calling undefined function etc.

note: try catch block does not handle syntax errors.

JavaScript provides error-handling mechanism to catch runtime errors using try-catch-finally block, similar to other languages like Java or C#.

  • try: wrap suspicious code that may throw an error in try block.
  • catch: write code to do something in catch block when an error occurs. The catch block can have parameters that will give you error information. Generally catch block is used to log an error or display specific messages to the user.
  • finally: code in the finally block will always be executed regardless of the occurrence of an error. The finally block can be used to complete the remaining task or reset variables that might have changed before error occurred in try block.


Example of Error handling in JS
try
{ var result = Sum(20, 30); // Sum is not defined yet
}
catch(ex)
{ document.getElementById("errorMessage").innerHTML = ex;
}

In the above example, we are calling function Sum, which is not defined yet. So, try block will throw an error which will be handled by catch block. Ex includes error message that can be displayed.

The finally block executes regardless of whatever happens.

Example of finally block:
try
{ var result = Sum(20, 20); // Sum is not defined yet
}
catch(ex)
{
document.getElementById("errorMessage").innerHTML = ex;
}
finally{
document.getElementById("message").innerHTML = "finally block executed";
}


throw

Use throw keyword to raise a custom error.

Example of throw error
try
{ throw "Error occurred";
}
catch(ex)
{ alert(ex);
}