Lesson Overview and Goal

Welcome back, stellar sailor! We've navigated through JavaScript landscapes, exploring error messages, syntax errors, and logical errors. Today, we'll learn about JavaScript exceptions and how to handle them using the try/catch mechanism. Exceptions are akin to unexpected events during the execution of your program — similar to receiving incorrect data input when working with a form submission on a web page. Let's embark on this fascinating exploration!

Introduction to JavaScript Exceptions

Exceptions are unexpected events that disrupt the normal flow of a program. Imagine typing a website's URL and landing on a page that wasn't supposed to be there. That's an exception! Seemingly, exceptions can halt program execution. Therefore, understanding exceptions and handling them effectively is vital for smooth program execution.

JavaScript exceptions are "special" error objects. When the JavaScript engine encounters unexpected situations or when we deliberately create an error using the throw statement, an exception gets thrown. The exception contains information about the error for effective debugging.

Let's consider a simple example:

let fruits = ["apple", "orange", "banana"];
console.log(fruits[3].toUpperCase()); // This will throw a error, as `fruits[3]` is `undefined`

Here, we're trying to log the uppercase value of the fourth item (index three) in an array that only contains three items. This leads to an exception of calling toUpperCase() on the undefined type.

Throwing Custom Errors

When an error state happens in the code, or whenever you feel you need this, you can also throw a custom error in your code. It's as simple as using a throw operator together with the Error, here is an example:

let balance = 100;
let pieces = 0;
if (pieces <= 0) {
    throw new Error("Balance can't be divided into negative non-positive number of pieces");
}
console.log("Divided balance:", balance / pieces);
Implementing Try/Catch Blocks

Think of controlling a spaceship. Errant asteroids, symbolizing exceptions, may damage your ship. In this lesson, we will learn about try/catch blocks — the equivalent of the spaceship’s handy shields — which allow us to navigate past these exceptions and prevent unexpected crashes.

In JavaScript, the try block contains the code that could potentially encounter an exception, while the catch block handles it. Check out this illustration:

const fruits = ["apple", "orange", "banana"];

try {
  console.log(fruits[3].toUpperCase()); // This will throw a error, as `fruits[3]` is `undefined`
} catch (error) {
  // Log avoided collision information
  console.log("Exception caught: " + error); // This message will be printed, indicating that an exception has been caught
  console.log("Error message: " + error.message);
}
// Prints:
// Exception caught: TypeError: Cannot read properties of undefined (reading 'toUpperCase')
// Error message: Cannot read properties of undefined (reading 'toUpperCase')

Here, we have successfully caught an exception caused by calling toUpperCase on the undefined type.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal