Did you find this useful?
Socialize it today.


JavaScript Try and Catch

Sunday, April 15, 2012

A good programmer should always try to manage run-time errors. There is nothing more frustrating for users of your application to encounter an unfriendly error. This also applies when programming in JavaScript. When users are browsing your webpages the last thing you want for them to encounter is a pop-up alert asking them if they wish to debug. While these error messages are great for developers, they are not for your users. Users will often leave the page when they come across these errors.

The try and catch statements will allow you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs. Here is an example of the syntax.


try
{
check (execute) this JavaScript code.
}
catch(err)
{
Run this JavaScript code if there were errors in the try block
}


Try Catch Example

In this next example, the JavaScript programmer intended to generate an alert box when the user clicks on the submit button. However, as you can see, there is a typo in the popup() function. The programmer intended to call alert(), but instead misspelled alert as alet(). A JavaScript error will occur when a user clicks on the button. If we use try and catch statements, the catch block will execute when the error occurs. The code in the catch block will execute and display a custom error message informing the user what happened.


<html>
<head>
<script type="text/javascript">
var txt = "";
function popup()
{
try
{
alet("Hello!");
}
catch (err) {
txt = "There was an error on this page. Sorry about that.\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
}
}
</script>
</head>

<body>
<input type="button" value="Click Here" onclick="popup()" />
</body>

</html>


Once you learn how to effectively use try and catch statements, there should be no reason why your users should receive system generated errors. In addition, you can incorporate other methods in your catch block that can include logging the error or sending out a notification.

Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

Professional JavaScript for Web Developers Murachs JavaScript and DOM Scripting HTML CSS and JavaScript Editor