JavaScript has many built-in error types, and you can create custom errors too.
🚨 Error Types:
• Error: Generic error
• SyntaxError: Invalid syntax
• ReferenceError: Invalid reference
• TypeError: Wrong type
• RangeError: Number out of range
javascript
// Different error types
function demonstrateErrors() {
// 1. ReferenceError
try {
console.log(undefinedVariable);
} catch (e) {
console.log(`${e.name}: ${e.message}`);
}
// 2. TypeError
try {
null.toString();
} catch (e) {
console.log(`${e.name}: ${e.message}`);
}
// 3. RangeError
try {
const arr = new Array(-1);
} catch (e) {
console.log(`${e.name}: Invalid array length`);
}
}
demonstrateErrors();
// Custom Error
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
function validateAge(age) {
if (age < 0 || age > 120) {
throw new ValidationError("Age must be between 0 and 120");
}
return `Valid age: ${age}`;
}
try {
console.log(validateAge(25));
console.log(validateAge(150));
} catch (error) {
console.log(`${error.name}: ${error.message}`);
}You should see
ReferenceError: undefinedVariable is not defined TypeError: Cannot read properties of null RangeError: Invalid array length Valid age: 25 ValidationError: Age must be between 0 and 120