Hi everyone! I'm the author of code.mu :)
I'd love to chat with my non-Russian audience. I'm looking for your feedback on the site and the translation quality. Let's chat:)
⊗jsSpExcThrUT 147 of 294 menu
◀ ▶

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.

← →
↑
English▼
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline