Error/Exception handling in jQuery

Your code is not working is a Daily Battle which I think we all deal with. But that's the best way to learn and become expert. You may read many books on technologies but you can't remember everything. But practical exposure and solving different error will always stay in your mind. So in this post, we will see how to handle errors in jQuery.


Related Post:

Lets admit Error occurs!!!!

It can be syntax errors, coding error, typo, errors due to wrong input, common mistakes and many other things. When an error occurs (if not handled), further execution of code is normally stopped, and an error message is generated (which is visible in status bar or console of browser). So it is best practice to always handle the errors. Or at least you must handle the error for those code blocks which are error prone.

How to handle?

To handle errors, you can use try...catch...finally with jQuery. Put your code within try block and the catch block will catch the error, and executes the code written in catch block. The syntax is quite simple.
try
{
  //Some code here
}
catch(e)
{
  //Handle errors here
}
[finally {
    // Code that is always executed regardless of 
    // an exception occurring
}]
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 (argument passed in catch block) and catch block is executed. The optional finally block executes unconditionally after try/catch.

Lets see an example. Below jQuery code performs divison of two variable iNumber1 and iNumber2. But in the alert statement, variable name is worng (typo, common mistake) which will produce an error.
try 
{
    var iNumber1 = 100;
    var iNumber2 = 20;
    alert(iNumber / iNumber2);
} 
catch (err) {
    alert('Some error occured while dividing');
}
So in this case, the catch block code will get executed, as try block throws an error. Remember catch block will get executed only when there is an error thrown by try block.

Along with try/catch block, there is one more option available which is throw statement. The throw statement allows you to create a custom error. It is like throwing an exception and catch block catches it.
try 
{
    var iNumber1 = 100;
    var iNumber2 = 0;
    var result = iNumber1 / iNumber2;
    if(isNaN(result))
        throw "Both numbers are 0";
    if(result == Infinity)
        throw "Divide by Zero";
} 
catch (err) {
    alert(err);
}
So in this case, based on the result of division different error will be thrown and displayed to user.

Other options

We can also take advantage of window.onerror() handler. "window.onerror" acts something like a global try/catch block. When there is an uncaught exception or compile-time error, the window.onerror event handler is called with contextual information about the error, making for some more powerful error handling opportunities. The syntax is,
window.onerror = function (message, filename, linenumber) {
    // Perform error reporting here, like logging error message 
    // with file name and line number on the server
    // for later processing. 
  
    return true; // The exception is handled, don't show to the user.
}
Here is an example,
function myFunction()
{
 var iNumber1 = 100;
 var iNumber2 = 20;
 var result = iNumber / iNumber2;
}

window.onerror = function (message, filename, linenumber) {
  alert("JS error: " + message + " on line " + linenumber + " for " + filename);
}
The "onerror" event handler can also be attached with image tags. The jQuery version of "onerror" handler is ".error()". For example, when the image is not loaded properly, you can use error handler on images to handle such images.
$('img').error(function() {
  $(this).hide();
});
Read "How to handle broken image using jQuery". error event may not work if you are testing it using file:// protocol. Instead, host it on web server and access using HTTP protocol.

So the best practice is to always handle jQuery errors and exception so that it doesn't interrupt page loading.

Feel free to contact me for any help related to jQuery, I will gladly help you.
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..