Simple Error Handling in Javascript

Simple Error Handling in Javascript

Errors in coding will inevitably happen. There are plenty of things that can go wrong when coding, be it from the programmer, the user, or other unexpected happenstance...we're only humans after all. The exception can be from a simple typo, a syntax error, or a logical error (the bane of my coding existence) amongst others. Fortunately, Javascript offers several ways to effectively handle errors so that your code doesn't break. In this post, I will be going over some of the basic ones including try...catch, finally, and throw.

JavaScript try...catch...finally Statement

Here is the basic syntax:

try {
  // the block of code to run
}
catch(error) {
  // the block of code to handle errors
} 
finally {
  // the block of code to be executed regardless of the result from try or catch
}

The try statement is the block of code that needs to be executed. The catch statement defines the block of code that is to be executed when an error occurs in the try block. If there is no error, the catch block is skipped. The finally statement is optional and will execute after the try block whether or not an exception was caught. The try statement can be used with just the catch clause or the finally clause, or both.

The Throw Statement

When an error pops up, we are usually presented with the name and message of the error. The throw statement allows for the creation of a custom error for the user. In this example, the variables a and b should only be positive integers.

function multiply (a, b) {
    if (a <= 0 || b <= 0) {
        throw "0 is not allowed";
    }

    return a * b;
}

Custom statements are useful for application-specific errors and provide better clarity for the user.

Putting It Together

try {
   let answer = prompt("Type yes to agree");

   if (answer !== 'yes') {
       throw new Error("You must agree to enter");
   }
}
catch(error) {
  alert(error.message);
} 
finally {
  alert("Thanks for visiting us!");
}

When we run this code, the user is presented with this prompt:

popup box.png

If the user does not type in "yes" as indicated, the custom error that we specified will show up.

error.png

The code then continues to run which results in the finally block executing. If the user does type in "yes", our code will skip over the catch block and go-ahead to run the finally code.

finally.png

Some Practical Uses

External data is a common source of errors. Poorly formatted JSON data can create errors in your code which can be handled with the try...catch statement.