JavaScript Try…Catch Statement

Posted on 21/09/2009 by


The try…catch statement basically allows you to test a block of code for errors.

Whenever your browsing the web pages on the internet, we’ve all seen a JavaScript alaet box telling us there is a runtime error and asking “Do you wish to debug?”.  Error messages like this are maybe useful for developers but not for users. When users normally see errors, they often leave the Web Page.

The try…catch Statement

The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs.

The Syntax will be:

//Run some code here
//Handle errors here

The try…catch is also written in lowercase letters. Using uppercase letters will generate a JavaScript error!

It shows that to alert “Welcome geust!” when the button is clicked. However there’s a typo in the message() function. alert() is misspelled as adddlert(). A JavaScript error occurs. The catch block catches the error and executes a custom code to handle it. The code displays a custom error message informing the user what happened.


<script type=”text/javascript”>
var txt=””;
function message()
adddlert(“Welcome guest!”);
txt=”There was an error on this page.\n\n”;
txt+=”Error description: ” + err.description + “\n\n”;
txt+=”Click OK to continue.\n\n”;

<input type=”button” value=”View message” onclick=”message()” />
<input type=”button” value=”Delete message” onclick=”message()” />
<input type=”button” value=”Save message” onclick=”message()” />



View Message
Delete Message
Save Message


Posted in: Coding, JavaScript