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 onError Event 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

In one of the previous lessons we have seen one of the two error handling techniques in JavaScript i.e. try...catch statement. In this lesson we are going to learn the second error handing technique in JavaScript i.e. through onError event.

Using the onError event we can specify JavaScript code that is executed whenever an error condition in our code arises.

We usually tie the onError event to the HTML body tag as under:

<body onError="someFunction()">

When an error is generated for some reason inside the body tag someFunction() will be called.

Code example follows:

<html>
<head>
<script type="text/JavaScript">
function generateError(number)
{
if (number == 0) {
throw "number equals zero"; // throws an error
}
}
function errorMsg() {
alert("Oh! an Error!");
}
</script>
</head>

<body onError="errorMsg()">
<script type="text/JavaScript">
generateError(0);
</script>

</body>

</html>

What happens if the error is generated in the head section? How can we trap an error that is generated by the code in the sections other then the HTML body tag?

Do not worry! JavaScript provides us with yet another way to handle this kind of situations. We can set the window.onerror property to our error handling function to achieve what we need. When we set the window.onerror property to our error handling function, our error handling function gets executed, whenever and wherever the error is generated in the code of our web page.

Code example follows:

<html>
<head>
<script type="text/JavaScript">
function generateError(number)
{
if (number == 0) {
throw "number equals zero"; // throws an error
}
}
function errorMsg() {
alert("Oh! an Error!");
}
window.onerror = errorMsg;
</script>
</head>

<body>
<script type="text/JavaScript">
generateError(0);
</script>

</body>

</html>


Next >>> Lesson No. 33: JavaScript String Object





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