Lesson 15. JavaScript Try…Catch Statement |
||||||||
51 views
JavaScript - Catching ErrorsWhen 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 trap and handle JavaScript error messages, so you don’t lose your audience. There are two ways of catching errors in a Web page:
Try…Catch StatementThe 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
Note that try…catch is written in lowercase letters. Using uppercase letters will generate a JavaScript error! Example 1The example below contains a script that is supposed to display the message “Welcome guest!” when you click on a button. However, there’s a typo in the message() function. alert() is misspelled as adddlert(). A JavaScript error occurs:
To take more appropriate action when an error occurs, you can add a try…catch statement. The example below contains the “Welcome guest!” example rewritten to use the try…catch statement. Since alert() is misspelled, a JavaScript error occurs. However, this time, 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 2The 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:
The onerror EventThe onerror event will be explained soon, but first you will learn how to use the throw statement to create an exception. The throw statement can be used together with the try…catch statement. |
| « Viral site lets workers tell off their bosses | Lesoon 16. JavaScript Throw Statement » |
| Posted on Wednesday, January 28th, 2009 at 5:14 pm under Javascript For Beginners | RSS 2.0 Feed | |