Javascript throw
Created By: chatGPT
JavaScript provides a way to signal an error in the code using the
throw
statement. This allows you to create custom error messages and halt the execution of the program or function when something goes wrong. Throwing errors helps in debugging and managing exceptions in your code effectively.function checkNumber(num) {
if (num < 0) {
throw new Error('Negative number is not allowed!');
}
return num;
}
try {
console.log(checkNumber(-5));
} catch (error) {
console.error(error.message);
}
When you throw an error, you can catch it using the
try...catch
statement. This allows you to handle the error gracefully instead of letting the program crash. In the example above, if a negative number is passed, the throw
statement creates a new Error
object, which is then caught in the catch
block.function getUser(id) {
if (id <= 0) {
throw new Error('Invalid user ID!');
}
return { id: id, name: 'John Doe' };
}
try {
console.log(getUser(-1));
} catch (error) {
console.log('Error:', error.message);
}
You can also use
throw
in custom functions to enforce certain conditions. This practice is helpful in ensuring that data meets specific requirements before proceeding with further processing.function setAge(age) {
if (age < 0 || age > 120) {
throw new RangeError('Age must be between 0 and 120.');
}
return age;
}
try {
console.log(setAge(200)); // Will throw an error
} catch (error) {
console.log('Error:', error.message);
}
In addition to
Error
, you can create your own error types by extending the built-in Error
class. This allows you to define more specific error messages and manage different error types effectively.class CustomError extends Error {
constructor(message) {
super(message);
this.name = 'CustomError';
}
}
function validateInput(input) {
if (!input) {
throw new CustomError('Input cannot be empty!');
}
}
try {
validateInput(''); // Will throw a CustomError
} catch (error) {
console.log(`${error.name}: ${error.message}`);
}