Go Back   Wiki NewForum | Latest Entertainment News > Career Forum & Tips > Tech Forum & Tutorial > Java Forum & Tutorial


JavaScript Try...Catch Statement


Reply
Views: 1857  
Thread Tools Rate Thread
  #1  
Old 05-03-2009, 05:40 PM
welcomewiki welcomewiki is offline
Member
 
Join Date: Dec 2008
Location: India
Posts: 80,566
Default JavaScript Try...Catch Statement

The try...catch statement allows you to test a block of code for errors.
JavaScript - Catching Errors

When browsing Web pages on the internet, we all have seen a JavaScript alert box telling us there is a runtime error and asking "Do you wish to debug?". Error message like this may be useful for developers but not for users. When users see errors, they often leave the Web page.


This chapter will teach you how to catch and handle JavaScript error messages, so you don't lose your audience.


The try...catch Statement

The try...catch statement allows 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.


Syntax

try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}

Note that try...catch is written in lowercase letters. Using uppercase letters will generate a JavaScript error!


Example 1

The example below is supposed to alert "Welcome guest!" when the ****on 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:




Example














Example 2

The next example uses a confirm box to display a custom message telling users they can click OK to continue viewing the page or click Cancel to go to the homepage. If the confirm method returns false, the user clicked Cancel, and the code redirects the user. If the confirm method returns true, the code does nothing:




Example












Reply With Quote
Reply

New topics in Java Forum & Tutorial





Powered by vBulletin® Version 3.8.10
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
WikiNewForum)