Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

JavaScript Error and Exception Handling

In this article you will learn to fix errors in JavaScript and work with Exception Handling

In order to write a good code and to develop a successful application one should take care of the Errors and Exceptions in the code.

Error and exception, are many times used interchangeably. An error is an event that happens during the code execution and interrupts the normal flow of code which creates an exception object. When an error occurs, the program searches for an exception handler which is a block of code that handles the exception.

In other way, an error is the event and an exception is the object that the event creates.

The main reason behind errors and exceptions are failure of resources, user error, and programming logic failure. These errors are related to how the code is performing any specific task. They do not relate to the purpose of the task.

Types of error

Errors are of following types.

  1. Syntax error
  2. Runtime error
  3. Logical error

Syntax error

It is the error which occurs due to incomplete or incorrect code statement and does not follow on or more sytactical rule.

JavaScript syntax erros occurs at interpret time and also known as parsing errors.

Following example code demonstrate the JavaScipt syntax error.

Listing 1: Representing theJavaScipt syntax error.

<script type="text/javascript">
<!--
alert("Syntax error!"
//-->
</script>

In case of syntax errors in JavaScript, only the code which is in same thread where the syntax error occured, is affected. If there is other threads running concurrently there code will execute taking in account that there is no dependecy on first thread.

Some common syntax errors are listed bellow.

Missing or Mis-Matched Braces, Parenthesis, or Brackets

     Ex. window.print(;

Missing or Mis-Matched Quotes

     Ex. var x = 'It's a beautiful day';

Missing semi-colons

Ex. var x=5
var y=10

Runtime error

It is the error which occurs during execution of the code. It occurs when code tries to perform some action and the system, can not execute it.

It is also known as Exception.

Following example code demonstrate the JavaScipt runtime error.

Listing 2: Representing theJavaScipt runtime error.

<script type="text/javascript">
<!--
window.callonphone();
//-->
</script>

In above example, syntax is correct but it will cause a runtime error because it will try to call a metthod at runtime which does not exist.

Some common runtime errors are listed bellow.

Incorrect Capitilization(Case senstiveness)

Ex.  GetElementById(); //

Referencing code, functions or DOM objects before they exist

 Ex. <BODY onload="loadFunction();>

Using a reserved word

Ex. var for = 5;

Using a missing parameter

Logical error

Logical errors are due to logical mistakes in programming and are dificult to track. It is not sytax or runtime error. Due to this error code will not give the desire result.

Because logic totaly depends upon business logis, this can not be catched.

Error handling mechanism

By using following mechanism we can handle errors in java script.

The try-catch-finally Statement

This statement can catch the programmer generated and the runtime exceptions but can not the syntax errors.

Bellow is the syntax of try- catch block

Listing 3: Representing the syntax of try-catch statement

<script type="text/javascript">
<!--
try {
// Code to run
    [break;]
} catch( e ) {
// Code to run if an exception occurs
    [break;]
}[finally {
// Code that is always executed regardless of 
// an exception occurring
}]
//-->
</script>

The try block must be followed by at least one catch block and/or one finally block. When an exception occurs in the try block, the exception is placed in e and the catchblock is executed. The optional finally block executes unconditionally after try/catch.

Listing 4: Representing an example of try-catch statement

<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;

try {
alert("Value of variable a is : " + a );
}catch ( e ) {
alert("Error: " + e.description );
}finally {
alert("Finally block will always execute!" );
   }
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

Above example is trying to call a function which does not exist thus causing exception.

Nested try-catch-finally statements

Nested try-catch-finally statements can also be used to catch the errors inside the catch block.

Listing 5: Representing an example of Nested try-catch-finally statement

try {
document.write("Outer try running...<br/>");

try {
document.write("Nested try running...<br/>");
thrownew Error(301, "an error");
    }
catch (e) {
document.write("Nested catch caught " + e.message + "<br/>");
throw e;
    }
finally {
document.write("Nested finally is running...<br/>");
    }
}
catch (e) {
document.write("Outer catch caught " + e.message + "<br/>");
}
finally {
document.write("Outer finally running");
}

The throw Statement

Throw statement can be used as to raise the built-in or customize exception which can be captured latter.

Listing 6: Representing an example of throw statement

<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
var b = 0;

try{
if ( b == 0 ){
throw("Divide by zero error."); 
}else{
var c = a / b;
}
}catch ( e ) {
alert("Error: " + e );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

An exception can be raised in one function using a string, integer, Boolean or an object. We can capture that exception either in the same function or in other function using try...catch block.

Using the onerror event

We can use onerror event to handle the errors in the page.

Listing 7: Representing the use of onerror event

<html>
<head>
<script type="text/javascript">
<!--
window.onerror = function () {
alert("An error occurred.");
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

The onerror event provides following information.

  • Error message
  • URL
  • Line number

Listing 8: Representing the use of onerror event

<html>
<head>
<script type="text/javascript">
<!--
window.onerror = function (msg, url, line) {
alert("Message : " + msg );
alert("url : " + url );
alert("Line number : " + line );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me"onclick="myFunc();" />
</form>
</body>
</html>

Listing 9: Representing the use of onerror event

<imgsrc="image.gif"
onerror="alert('An error occurred loading the image.')" />

Handling multiple types of exceptions

We can handle multiple exceptions in single catch block with the help of if condition

Listing 10: Representing the handling ofmultiple types of exceptions

for (variCounter = 0; iCounter< 3; iCounter++) {
// Try/catch here in the loop so that if
// DoWork throws an exception, the loop
// will continue on
try {

DoWork(iCounter);

    }
catch (e) {

// Test for our own specific error
// conditions
if (e == "ItemNotFoundException") { HandleItemNotFoundException(e); }

elseif (e == "InvalidCredentialsException") { HandleInvalidCredentialsException(e); }

elseif (e == "InvalidDateException") { HandleInvalidDateException(e); }

// We didn't hit one of our own exception
// conditions above so this one isn't
// ours. Handle the standard error...
else { LogSystemError(e); }

    }
}

// Simply a function to throw a different
// exception string for each iCounter value
// passed in (simulate some errors)
functionDoWork(iCounter) {
if (iCounter == 0) { throw"ItemNotFoundException"; }

elseif (iCounter == 1) { throw"InvalidCredentialsException"; }

elseif (iCounter == 2) { throw"InvalidDateException"; }
}

AJAX error handling

XMLHttp requests can have different type of error. We can test for this by checking the status of our XMLHttp object

Listing 11: Representing the ajax error handling

functionprocessingFunction() {
if (oXml.readyState != 4) return; // our request is not done

switch (oXml.status) {
case 0: case 200: // request is good
break;
case 408: case 504: // request timed out
// code
break;
default: // request error
// code
return; // you will probably want to exit
break;
    }

// continue with the request
}

Conclusion

In this article we learnt the handling of error and exception, if you have any question, please let me know in the comments below.

Hope you liked the article, see you next time.



Have total 6+ years of experience in developing enterprise applications using DOT.NET 3.5 and 4.0(C#, VB.NET, ADO.NET, ASP.NET),java, JQuery, JSON, LINQ,WCF, MVC3, MVC4, Silverlight, SQL Server, mobile applications and Oracle etc ...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login