www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons JavaScript Error Handling using Try...Catch Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
Lesson 24
Lesson 25
Lesson 26
Lesson 27
Lesson 28
Lesson 29
Lesson 30
Lesson 31
Lesson 32
Lesson 33
Lesson 34
Lesson 35
Lesson 36
Lesson 37
Lesson 38
Lesson 39
Lesson 40
Lesson 41
Lesson 42
Lesson 43
Lesson 44
Lesson 45
Lesson 46
Lesson 47
Lesson 48
Lesson 49

Error handling in JavaScript is done through the use of the try...catch statement. The try statement marks a block of statements, expected to generate error(s) and the catch statement provides code handle the error(s).

The type of error that we can handle through the use of try...catch statements, are referred to as Exceptions in JavaScript. When an error of such kind is generated we say that an exception has been thrown. The catch part of the try...catch statement then catches such exception(s).

Besides using the try...catch statement to handle errors we also have the onError event in JavaScript to handle errors. In this lesson we will learn to use the try...catch statement. The onError event will be discussed lated.

More formally the try...catch statement allows us to test a block of code for errors and write code for error handling, if one is found. The syntax of try...catch statement follows:

//code, expected to generate error, goes here
//Error handling code goes here

The code example below illustrate the usage of try...catch statement:

<script type="text/JavaScript">
function printMessage()
aletr("Hello World! "); // alert() function delibrately misspelled
alert("This line is not executed"); // this line of code will not be executed
alert("There was an error on this page." + error.description);

<input type="button" value="Greetings" onclick="printMessage()" />


The code in the try block above throws an exception, due to the misspelling of the alert(), written as alert(), which is then handled by the catch block. The catch block alert the user about the error. Remember that any code after the error generating line of code in the try block does not execute. The error argument in the parenthesis of the catch clause is a built-in JavaScript object that contains information about the error.

Next >>> Lesson No. 31: JavaScript throw Statement

Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.