Throwing an exception in JavaScript

In the previous lessons, we've explored two places where JavaScript throws an exception when something goes wrong.

However, there may be other situations in your project that are exceptional for you but not for JavaScript. In this case, we can create and throw our own custom exceptions.

Let's explore the syntax required for this. First, you need to create an exception using the new Error command, passing the text of the exception as a parameter:

new Error('an exception text');

This exception must then be thrown using the throw command:

throw new Error('an exception text');

Throwing an exception causes JavaScript to think that an exception has occurred. This means that such an exception can be caught using the try-catch construct and handled as needed.

Let's look how to use it at an example. Suppose we have a function that divides one number by another:

function div(a, b) { return a / b; }

Let's assume that division by zero is forbidden and an exception should be thrown when trying to do this. To do this, we will check in the function if there is an attempt to divide by 0. If not, we will divide, and if yes, we will throw an exception:

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

Let's just try to divide by 0 first without catching the exception:

alert( div(3, 0) );

In this case, the script execution will be interrupted and an error will appear in the console with the 'division by zero error' text (check it). Let's now catch our error and handle it somehow:

try { alert( div(3, 0) ); } catch (error) { alert('you are trying to divide by 0, which is forbidden'); }

In JavaScript, trying to extract the square root of a negative number doesn't result in an exception being thrown:

let result = Math.sqrt(-1); console.log(result); // shows NaN

Write your own function that will extract the root from a number and at the same time throw an exception if the root is extracted from a negative number.

enru