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.

check (execute) this JavaScript code.
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.

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

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


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.

Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

HTML CSS and JavaScript Editor Professional JavaScript for Web Developers JavaScript and jQuery: The Missing Manual