Error Handling in JavaScript using Try...Catch Statement
The try...catch statement in Javascript enables web developers handle javascript errors within a block of code.
While browsing on the web, we frequently get javascript alert messages indicating that a runtime error has occured. And the browser message box also asks for whether you wish to debug the application or not. Of course, you can set configuration parameters of your web browser application such as Internet Explorer, Firefox or your Avant browser to supress javascript error messages or disable script debugging options. I'm sure, facing such an error message while browsing on the net will not please you and cause negative feelings about the site. Although this error information is very useful for developers who are maintaining the site or responsible for the development of the site, but means nothing for an ordinary web user. So as web developers, in order to keep our guests on our site, we should handle such errors as much as we can.
Error Catching and Handling Errors in Javascript
If you have used try...catch error handling methods in your ASP.NET application you will realize that Javascript syntax of try-catch-finally is very similar.
Try-Catch Syntax:
Let's make an example and see how we can trap javascript errors using try catch.
Open an empty web page and place the below code within the web page.
This javascript code will cause the following error on an Internet Explorer 7.0 browser.
So in order to handle this javascript error, let's change our script as follows using the try...catch error handling method.
The Javascript code which displays the value of the object using the alert() method fails. But since it is placed within a try block, the catch block of code executes and handles the error which is encapsulated in the err object.
We can even go further by using the error object err and its properties like "description". You can write your code so that it behaves according to the description of the err object by testing err.description with conditional statements.
For example, the above error has the description, "Object required".