Register to get access to free programming courses with interactive exercises

Exceptions JS: Dive into Classes

Exceptions are one of the few examples of the successful use of inheritance. In this lesson, we will learn how to create exceptions and intercept them.

Usually, we use exceptions like this. Closer to the beginning of the program is the try/catch construct, which catches exceptions and shows the user an adequate message:

try {
  doSomethingDangerous();
} catch (e) {
  console.log(e);
}

But how do you know what is wrong? Sometimes, it is important, because errors can lead to different program behavior. In addition, not all errors require processing at the current point in the program.

You can separate errors using different classes that inherit from the Error class:

// This method works only if Babel isn't used
class MyError extends Error {}
class AnotherError extends MyError {}

And unlike other inheritance examples, exceptions rarely need to add or change behavior. The main purpose of using exception inheritance is to describe all possible types of errors.

Now let's see how we can take advantage of it:

try {
  // Some code that might throw an exception
} catch (e) {
  if (e instanceof MyError)
    // Doing something
  else if (e instanceof SomeError) {
    // Doing something else
  }

  // In all other cases, we do something like throwing an exception again
  throw e;
}

Hijacking any base exception entails automatically hijacking all descendants of the current class. For example, if you catch MyError in a catch block, that block will catch objects of that class and objects of all its descendants.

Almost every programming language has an unspoken rule about exception hierarchies. Any program must define its high-level exception, inherited from Error. All other library exceptions are inherited from it. This approach allows you to isolate the error handling of a particular library with just one catch block.

But not all libraries in JavaScript use inheritance. The point is that before the es6 standard, there were no classes and no easy way to create descendants from the Error constructor. And, since many libraries still fit in the old standard they solve the problem of determining the error type using a common property:

import axios from 'axios';

try {
  client.get('https://hexlet.io');
} catch (e) {
  if (e.isAxiosError) {
    // All axios library errors will go here
  }

  // Processing other errors
}

finally block

In some situations, the program may need to continue working regardless of whether an exception has occurred. If we only use try/catch, we can't do this without duplication. You should put code both after the whole try/catch construct and in every catch block.

It has led to an expansion of the design itself, adding the finally block. We call this block at the very end in every case:

try {
  // Some code
} catch (e) {
  // Doing something
} finally {
  // Called in any case
}

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY
Suggested learning programs
profession
Development of front-end components for web applications
10 months
from scratch
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.