JavaScript Error Handling

Jeff Gosselin
Nov 2 · 2 min read

As a developer, you know that errors are unavoidable. Errors are bound to happen whether it is due to a network connection issue, an invalid user entry, incorrect data being sent or received from a server, a reference to an object/function that doesn’t exist, or because of bad syntax in the code.

Try, Catch, Finally, and Throw

try {} — Allows you test a block of code for runtime errors. As soon as an error is reached within the try code block, code execution will be immediately transferred over to the catch block. If there aren’t any errors the catch block will be ignored.

catch {} — Allows you to handle errors. This code block is executed if there is an error in the try block of code.

throw {} — Allows you to create custom errors.

finally {} — This block of code executes regardless of the try and catch result.

Let’s take a look at an example of all this in action:

function rectArea(width, height) {
if (isNaN(width) || isNaN(height)) {
throw "Parameter is not a number!";
} else {
return width * height;
}
}
let areaOfRect;try {
console.log("Hello!");
areaOfRect = rectArea(2, 'c');
console.log("Goodbye!");
} catch(err) {
console.log(err);
} finally {
console.log("I will always be executed.")
}

Here is the output of that code:

Hello!
Parameter is not a number!
I will always be executed.

Let’s breakdown what we see above…

  1. We declare a function called rectArea that takes 2 arguments, width and height. Inside of that function we have an if statement that tests to see if either argument is not a Number. If that is true , we throw a custom error. Once that error is thrown, the execution of the current function ceases and the custom throw error will be executed in the catch block.
  2. We declared a variable named areaOfRect.
  3. In the try block we have 3 things happening. We first log “Hello!”, then set our areaOfRect variable to the result of the rectArea function, and lastly you’ll notice a console.log of “Goodbye!” According to our code above, when the rectArea function is called with a string as one of the arguments, it will throw an error. Therefore, the console.log of “Goodbye!” does not execute and the custom error message of “Parameter is not a number!” get logged.
  4. Finally the finally block, regardless of the try and catch result will execute. So it logs “I will always be executed.”
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade