Js throw new error
A simple but important topic!
In JavaScript, throw
is a keyword that is used to throw an exception, which is an object that represents an error or an unexpected condition. When an exception is thrown, it interrupts the normal flow of execution and transfers control to the nearest catch
block.
Here's the basic syntax:
throw new Error(message);
Where message
is a string that describes the error.
For example:
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero!");
}
return a / b;
}
try {
console.log(divide(10, 0)); // throws an error
} catch (error) {
console.error(error.message); // outputs "Cannot divide by zero!"
}
In this example, the divide
function throws an Error
object when it encounters a division by zero. The try
block attempts to execute the divide
function, but since it throws an error, control is transferred to the catch
block, where the error message is logged to the console.
Note that throw
can also be used with other types of objects, not just Error
objects. For example:
throw { name: "MyError", message: "Something went wrong!" };
This would throw a custom error object with a name
property set to "MyError"
and a message
property set to "Something went wrong!"
.
It's worth noting that throw
can also be used in a try
-catch
block to re-throw an error that was caught:
try {
// code that might throw an error
} catch (error) {
throw error; // re-throw the error
}
This can be useful when you want to catch an error and then re-throw it, perhaps to propagate it up the call stack or to handle it in a different way.