Tackling Run Time Errors in JavaScript

There is an old-saw:

With every solution comes the new problem.

It can be applied on various aspects of life, but right now, I am more concerned about the life of programmers. They(programmers) are always curious to solve problems, but while solving them, they encounter various hurdles.

If I talk solely about programming world, there are problems that arise while solving the some other problem. That problem is in the shape of bugs, exceptions, error etc. Therefore, in this article, I shall address certain kind of problems that arise while coding in JavaScript, and how to handle them.

Run Time Error Handling

As JavaScript is a loosely-typed language, meaning there are no specific types of identifiers for some specific data, the chances of getting errors in such loosely-typed language get proliferated. Run time error is one of them.

In order to tackle the run-time error, there is a try-catch-finally block available. try-catch-finally block is used to handle the run-time errors.

Syntax of try-catch-finally:

try
{
    // code that has a potential to throw an error
}
catch(ex)
{
    // If error in try block occurs, catch will be executed
}
finally{
    // Finally executes ALWAYS whether or not error occurs in the try block
}

Keywords of try-catch-finally

  • try: A block of code that has a potential to cause an error is wrapped by try.
  • catch: When an error occurs, this block executes. Usually a notification or a warning is initiated from this block.
  • finally: This block will always execute regardless of the occurrence of an error.

Example

Not Always True Scenario: Catch-Block invokes

try
{
    var result  =  thereThere(10, 20); // Therethere is not defined 
}
catch(error)
{
    document.getElementById("errorMessageHolderID").innerHTML = error;
}

In the above example, we are calling function thereThere, which is not defined . So, try block will throw an error which will be handled by catch block. Error includes error message that can be displayed.

Always True Scenario: Finally Block Invokes

The finally block executes regardless of whatever happens.

try
    {
        var result  =  thereThere(10, 20); // Therethere is not defined 
    }
    catch(error)
    {
        document.getElementById("errorMessageHolderID").innerHTML = error;
    }
    finally {
        document.getElementById("lightBlinking").innerHTML = "Ting Tong."
    }

Whether there is an error or not, you will get "Ting Tong" on your web page always.

Summary

In this article I have discussed how to handle run-time errors in JavaScript by using try-catch-finally block. I hope you understand the gist behind try, catch and finally keywords. That is it for this article!

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Join our community!

Delete an article

Deleted articles are gone forever. Are you sure?