Skip to main content

Error Handling in JavaScript

There are three types of errors in programming: (a) Syntax Errors and (b) Runtime Errors (c) Logical Errors:

Syntax errors:

Syntax errors, also called parsing errors, occur at compile time for traditional programming languages and at interpret time for JavaScript.
For example, the following line causes a syntax error because it is missing a closing parenthesis:
<script type="text/javascript">
<!--
window.print(;
//-->
</script>
When a syntax error occurs in JavaScript, only the code contained within the same thread as the syntax error is affected and code in other threads gets executed assuming nothing in them depends on the code containing the error.

Runtime errors:

Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).
For example, the following line causes a run time error because here syntax is correct but at run time it is trying to call a non existed method:
<script type="text/javascript">
<!--
window.printme();
//-->
</script>
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal execution.

Logical errors:

Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and you do not get the result you expected.
You can not catch those errors, because it depends on your business requirement what type of logic you want to put in your program.

The try...catch...finally Statement:

The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try...catch...finally construct as well as the throw operator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.
Here is the try...catch...finally block syntax:
<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 either exactly one catch block or one finally block (or one of both). When an exception occurs in the try block, the exception is placed in e and the catch block is executed. The optional finally block executes unconditionally after try/catch.

Examples:

Here is one example where we are trying to call a non existing function this is causing an exception raise. Let us see how it behaves without with try...catch:
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
   var a = 100;

   alert("Value of variable a is : " + a );
 
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

Now let us try to catch this exception using try...catch and display a user friendly message. You can also suppress this message, if you want to hide this error from a user.
<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 );
   }
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

You can use finally block which will always execute unconditionally after try/catch. Here is an example:
<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>

The throw Statement:

You can use throw statement to raise your built-in exceptions or your customized exceptions. Later these exceptions can be captured and you can take an appropriate action.
Following is the example showing usage 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>

You can raise an exception in one function using a string, integer, Boolean or an object and then you can capture that exception either in the same function as we did above, or in other function using try...catch block.

The onerror() Method

The onerror event handler was the first feature to facilitate error handling for JavaScript. The error event is fired on the window object whenever an exception occurs on the page. Example:
<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 handler provides three pieces of information to identify the exact nature of the error:
  • Error message . The same message that the browser would display for the given error
  • URL . The file in which the error occurred
  • Line number . The line number in the given URL that caused the error
Here is the example to show how to extract this information
<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>
You can display extracted information in whatever way you think it is better.

You can use onerror method to show an error message in case there is any problem in loading an image as follows:
<img src="myimage.gif"
    onerror="alert('An error occurred loading the image.')" />
You can use onerror with many HTML tags to display appropriate messages in case of errors.

Comments

Popular posts from this blog

HTTP Status Code 501 - Not Implemented

501 Error Code Explained The server either does not recognise the request method, or it lacks the ability to fulfill the request. Why it occurs The error occurs when the Web server does not understand or does not support the HTTP method it finds in the HTTP data stream sent to it by the client. The method in the request HTTP data stream should be one of the following GET, OPTIONS, HEAD, POST, PUT, DELETE, TRACE and CONNECT as defined by the HTTP protocol Or the method may be valid but not actually supported by the Web server. Fixing 501 error code The client should specify a valid request type. Even after that if the Web server is responding incorrectly, then the web server simply needs to be upgraded to fix the issue. If you are registered with 100pulse, your site will be monitored and you will be intimated by an email or a short message service when 501 status code error occurs.

Optimize MySQL query with STRAIGHT_JOIN

Before finalizing my queries, I use MySQL Workbench to explain it to make sure the performance is good. I always notice that the performance of the queries with joins on multiple tables varies at times. Then I start indexing my tables to make sure that the Explain is happy and scanning minimum records before handing over the data. But with one of my query, even after adding an appropriate index I was not getting the performance I was expecting. I asked Workbench to explain the query and what? MySQL was not using my newly added index which could optimize the query. I tried FORCE INDEX and MySQL liked it. It started using the index which I forced it to. But I was not happy at forcing MySQL to use my index. I wanted it to do it itself. After researching a bit, I came across STRAIGHT_JOIN and without wasting any time, I added it to my query and what? MySQL started using my index without being forced to. Now the question was, how the STRAIGHT_JOIN works and is different from INNER JOIN. Wit

In Java, what’s the difference between method overloading and method overriding?

The difference between overriding and overloading in Java is a common source of confusion – but it is fairly simple to understand. Let’s start the discussion by talking more about method overloading. Overloading in Java  can  occur when two or more methods in the same class share the same name or even if a child class shares a method with the same name as one of it’s parent classes. But, in order to  actually  have overloaded methods, the methods not only have to have the same name, but there are other conditions that must be satisfied – read below to see what those conditions are. Suppose we have a class called TestClass which has 2 methods, and both methods have the  same  name – let’s say that name is “someMethod” – this would be considered to be method overloading if  at least one of these 2 things is true: 1.) The number of parameters is different for the methods 2.) The parameter types are different. How to NOT overload methods: It’s important to underst