JavaScript Error Handling

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…
- We declare a function called
rectAreathat takes 2 arguments, width and height. Inside of that function we have anifstatement that tests to see if either argument is not aNumber. 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 thecatchblock. - We declared a variable named
areaOfRect. - In the
tryblock we have 3 things happening. We first log“Hello!”, then set ourareaOfRectvariable to the result of therectAreafunction, and lastly you’ll notice aconsole.logof“Goodbye!”According to our code above, when therectAreafunction is called with a string as one of the arguments, it will throw an error. Therefore, theconsole.logof“Goodbye!”does not execute and the custom error message of“Parameter is not a number!”get logged. - Finally the finally block, regardless of the
tryandcatchresult will execute. So it logs“I will always be executed.”
