If necessary, we ourselves can generate errors and determine the conditions when an error will be generated.
Consider an example:
class Person { constructor(name, age) { this.name = name; this.age = age; } print() { console.log(`Name: ${this.name} Age: ${this.age}`); } } const tom = new Person("Tom", -123); tom.print(); // Name: Tom Age: -123
Based on common sense, we understand that age cannot be negative. Nevertheless, for the time being, based on the logic of the class, nothing prevents us from passing a negative value for age to it when creating a Person object.
How to fix this situation? There are various ways, and one of them is to throw an exception.
To generate an exception, the throw statement is used, after which information about the error is indicated.
The error information can represent any object.
So, let’s throw an exception when passing a negative value for the age property to the Person constructor:
class Person { constructor(name, age) { if (age < 0) throw "Age must be greater than 0"; this.name = name; this.age = age; } print() { console.log(`Name: ${this.name} Age: ${this.age}`); } } const tom = new Person("Tom", -123); // Uncaught tom.print();
As in the general case, we can handle this error with a try…catch block:
class Person { constructor(name, age) { if (age < 0) throw "Age must be greater than 0"; this.name = name; this.age = age; } print() { console.log(`Name: ${this.name} Age: ${this.age}`); } } try { const tom = new Person("Tom", -123); // Uncaught Age must be greater than 0 tom.print(); } catch (error) { console.log("Error"); console.log(error); // Age must be greater than 0 }
Errors types in JavaScript. Error Object. Code examples
September 6, 2022