- We can throw errors using
throw statement.
- Used to generate custom errors
- You can throw any type of object, but it's common to throw
Error objects for clarity & standardization.
- Try Catch Javascript
- In case of async functions you can also return
Promise.reject() with anything as parameter for the error case.
Syntax
throw expression;
Example 1: Throwing a custom error
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed");
}
return a/b;
}
try {
divide(4, 0);
} catch(error) {
console.error(error.message); // Output: Division by zero is not allowed
}
Example 2: Throwing custom objects
function login(username) {
if (!username) {
throw { message: "Username is required", code 400};
}
return "Logged in!";
}
try {
login("");
} catch (error) {
console.error(error.message); // Output: Username is required
}