Imagine this scenario

Let’s say you have a function from an external JS library you need to use. You need to pass to this function a dynamic variable that can contain many possible values.

Now suppose that this external function doesn’t support all values and doesn’t have a proper fallback in case of an unknown value. The function just crashes and an exception is thrown.

This can affect the rest of the code and even break the page completely.

It’s also impossible to cover all the scenarios and address each and every one of them specifically. Especially if you use an external function over which you have no control.

So how can we avoid these issues?

The “try…catch” logic

This simple try-and-catch method allows you to decide on how you handle errors. All errors.

try {
	// Code to check.
} catch (error) {
	// An error occurred. Let's handle this.
}

If you are not sure whether a code can cause an error, just place it inside the try section. It will try to run this code in a “safe zone”. If no errors occurred - we’re good to go, and the code will just work.

If, however, it causes an error, it will automatically skip to the catch section without passing these errors to the end user.

In the catch section, errors can be handled individually (depending on the error that occurred), or in general (such as displaying a general error message to the user).

The “finally” section

There’s also a finally section.

The code inside this section will always run for all users, whether we have an error (catch section) or not (try section was completed successfully). This section is optional if a catch section is included.

try {
	// Code to check.
} catch (error) {
	// An error occurred. Let's handle this.
} finally {
	// This always runs.
}

Skip error handling

You may want to skip error handling and simply avoid this part of the code completely in case of an error.

To do this, an empty catch section must be provided:

try {
	// Code to check.
} catch {}

Alternatively, the finally section should be included:

try {
	// Code to check.
} finally {
	// This always runs.
}

References