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 is very similar.
Try-Catch Syntax:
try
{
// Place here javascript code that you want to handle errors with
}
catch
{
// Place error handling code here
}
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.
<script>
var nonExistingElement;
nonExistingElement = document.getElementById("notexists");
alert(nonExistingElement.Value);
</script>
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.
<script>
var nonExistingElement;
nonExistingElement = document.getElementById("notexists");
try
{
alert(nonExistingElement.Value)
}
catch(err)
{
if (nonExistingElement == null) {
alert('notexists is null')
}
}
</script>
The
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"
BlinkList
Del.icio.us
Digg
Furl
Simpy
Spurl
DZone
ma.gnolia
Shadows
|