This article explains how you can handle errors in JavaScript using Try-Catch statements. It also explains how you can throw your own errors using the Throw statement with examples.
Debugging in JavaScript
Now that we have covered almost all the basics of JavaScript including advanced operators, conditional statements, looping constructs, alerts and functions, we move on to exception or error handling in JavaScript. All of us must be familiar with JavaScript errors that either stop the page from loading completely or prompt us to enter the JavaScript Debug console to rectify the error.
These errors occur when the JavaScript code hasn’t been written properly. As JavaScript is an interpreted and not a compiled language, we cannot know where the error lies until we test run it. Even then, in cases concerning user input, errors can creep in if the user enters a null value and the required cases are not taken into consideration by the programmer.
Normally, if there is an error in the JavaScript code, the code executes until that point and the page stops loading where the error occurs. The error is generally not directed at the user level but at the developer level. Here’s how you can handle such errors without letting the user know that anything went wrong.
Error Handling in Javascript
The basic error handling mechanism in Javascript is the try .. catch statement.
Try Catch Statement
The try catch statement allows you to test your code for errors. All the code which needs to be checked for errors is placed in the try block. The code which handles the error condition in case there is an error goes into the catch block.
Here’s the basic syntax for the try catch statement
try
{code to be tried; if any error occurs, it is passed on to the catch statement. }
catch(errorvariable)
{error handling code}
Here’s an example:
docutypoment.write(“This is an error as document is misspelled as docutypoment.”);
This leads to an error in the page which prevents it from loading.
Now we use a try catch statement to handle the error.
try
{
docutypoment.write(“This is an error as document is misspelled as docutypoment.”);
}
catch(errorvariable)
{document.write(“An error occurred: Error details: “+errorvariable.description);
}