Quackit Logo

FREE Hosting!

With every domain name you register with ZappyHost, you get FREE hosting.

$1.99 Domain Names

With every new non-domain purchase thru ZappyHost, you get a domain name for only $1.99.

JavaScript Try... Catch

Print Version

The more JavaScript you code the more errors you'll encounter. This is a fact of life in any programming environment. Nobody's perfect and, once your scripts become more complex, you'll find there are sometimes scenarios that result in an error that you didn't think of.

JavaScript errors on web pages can scare your visitors away. How many times have you encountered a web page with errors, only to click the "back" button?

OK, so you can't always prevent errors from occuring, but you can do something about them. The JavaScript "Try... Catch" statement helps you handle errors in a "nice" way.

To use the Try... Catch statement, you take any code you think could potentially result in an error, and wrap it within the "try" statement. You then code what you want to happen in the event of an error and wrap that in a "catch" statement.

Code without a Try... Catch statement:

<script type="text/javascript">
<!--
document.write("My bank balance is $" + myBankBalance);
//-->
</script>

The above code will result in an error. This is because the variable "myBankBalance" hasn't been declared yet.

Code with a Try... Catch statement:

<script type="text/javascript">
<!--
try
{
document.write("My bank balance is $" + myBankBalance);
}
catch(err)
{
document.write("Sorry, an error has occurred");
document.write("...but hey, don't let that stop you!");
}
//-->
</script>

The resulting output:

The above code will hide the error and present something more user friendly to the user. This is because the code with the error was wrapped inside a "try" statement. And, because there was an error, the browser outputs whatever is between the "catch" statement.

Enjoy this website?

  1. Link to this page (copy/paste into your own website or blog):
  2. Add this page to your favorite social bookmarks sites:
               
  3. Add this page to your Favorites

Oh, and thank you for supporting Quackit!