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:

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 operator together with the , here is an example:

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