The throw operator is used in JavaScript to generate custom exceptions. It allows developers to create and throw their own errors in certain situations, making code more understandable and predictable. The throw operator can throw values of any type, but it’s recommended to use Error objects or their subclasses for compatibility with the try…catch construct.
Main use cases:
The throw operator is a key tool in JavaScript for managing error flow and generating custom exceptions. It works in conjunction with the try…catch construct, allowing for more robust and predictable code.
The throw operator immediately stops execution of the current function and transfers control to the nearest catch block:
function validateAge(age) {
if (age < 0) {
throw new Error('Age cannot be negative');
}
return age;
}One of the most common uses of throw is checking the correctness of input data:
function divide(a, b) {
if (b === 0) {
throw new Error('Division by zero is not possible');
}
return a / b;
}You can create specialized errors for different situations:
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = 'ValidationError';
}
}
function validateEmail(email) {
if (!email.includes('@')) {
throw new ValidationError('Invalid email format');
}
}function createUser(userData) {
if (!userData.name) {
throw new Error('User name is required');
}
if (!userData.email) {
throw new Error('User email is required');
}
// Create user...
}function changeUserStatus(userId, newStatus) {
if (newStatus !== 'active' && newStatus !== 'inactive') {
throw new Error('Invalid user status');
}
// Change status...
}The throw operator can throw values of any type:
// Strings
throw 'Error!';
// Numbers
throw 404;
// Objects
throw { code: 'INVALID_DATA', message: 'Invalid data' };
// Error instances (recommended)
throw new Error('Error message');// ❌ Not recommended
throw 'Validation error';
// ✅ Recommended
throw new Error('Validation error');// ❌ Error not handled
function badFunction() {
throw new Error('Error!');
}
// ✅ Proper handling
try {
badFunction();
} catch (error) {
console.error('An error occurred:', error.message);
}The throw operator is supported in all modern browsers and JavaScript runtime environments.
The throw operator is an important tool for creating reliable code, allowing you to explicitly signal problems and control the execution flow of the program when exceptional situations arise.
What will be output to the console and why?
function processData(data) {
if (!data) {
throw new Error('Data missing');
}
if (data.length === 0) {
throw 'Empty array';
}
return data.map(item => item * 2);
}
try {
console.log(processData([]));
} catch (error) {
console.log('Error:', error.message || error);
}Answer: Error: Empty array
Explanation:
It’s important to understand that throw can throw values of any type, but it’s recommended to use Error objects for better compatibility and consistency.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪