Mastering JavaScript Error Handling

Category App Development, Product engineering

Errors are bound to occur in any program/ software. Browsers, javascript do a pretty good job in handling errors. Javascript creates an object for any error. This object essentially has a name and a message. The name represents the type of error (Javascript has six types of errors). The object message provides useful information about the error. Javascript lets us do the error handling using try, catch and finally blocks.

Lets see a code snippet without try, finally block:

//Code Snippet:
counter = counter + 1;
testFunction();

function testFunction() {
console.log(“Function is executed”);
}

In the above code snippet, counter is not defined. Hence the first line of code will throw a reference error. The function “testFunction” is never called.

In a real time project, this could be fatal as a single reference error will stop the execution of code and application may stop responding.

Introducing try, finally block:

//Code Snippet:
try {
counter = counter + 1;
} finally {
testFunction();
}

function testFunction() {
console.log(“Function is executed”);
}

In the above code snippet, counter is not defined. Hence the try block will throw a reference error. Irrespective of the output in the try block, the finally block will be executed.

//Code Snippet:
var counter = 2;
try {
counter = counter + 1;
} finally {
testFunction();
}

function testFunction() {
console.log(“Function is executed”);
}

In the above code snippet, try block will not throw any error. As expected, the finally block will execute the code.

Introducing catch block:

//Code Snippet:
try {
counter = counter + 1;
} catch (exception) {
console.log(exception.message);
} finally {
testFunction();
}

function testFunction() {
console.log(“Function is executed”);
}

As mentioned earlier, Javascript provides an error object with name and message. This object can be passed as a param to the catch block. You can catch the error message, error name(type) from the exception object.

//Code snippet:
var counter = 2;
try {
counter = counter + 1;
} catch (exception) {
console.log(exception.message);
} finally {
testFunction();
}

function testFunction() {
console.log(“Function is executed”);
}

In the above code snippet, try block will not throw any error and catch block will not have exception to throw. As expected, the finally block will execute the code.

Ready to embark on a transformative journey? Connect with our experts and fuel your growth today!