Throwing custom exception types in JavaScript

The number of built-in in JavaScript exceptions is not that large, and they most often cannot satisfy all our needs for different types of exceptions. Therefore, JavaScript has the built-in ability to create exceptions with a custom type.

There are different ways to do this. The simplest one is to pass an object with the keys name and message to throw:

try { throw {name: 'MyError', message: 'an exception text'}; } catch (error) { console.log(error.name); // 'MyError' console.log(error.message); // 'an exception text' }

Previously, we made a function that throws an exception when dividing by zero:

function div(a, b) { if (b !== 0) { return a / b; } else { throw new Error('division by zero error'); } }

Modify this function so that it throws an exception with some kind of type we invented, for example, DivisionByZeroError.

Previously, you made a function that throws an exception when trying to extract the square root of a negative number. Modify your function so that it throws an exception with the type you invented. Think carefully about the name of the exception so that this name is successful.

enru