In JavaScript, throwing an error is a way to signal that something unexpected or wrong has happened in the code.
This can be helpful in debugging and preventing further execution of the program when an error occurs.
throw
statement:
The most common way to throw an error in JavaScript is by using the throw
statement. This statement allows us to throw an instance of an Error
object or a custom error object that we create.
For example:
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
console.log(divide(10, 0)); // throws an error
In the example above, we define a function called divide
that takes two arguments a
and b
. We use an if statement to check if b
is equal to 0
. If it is, we throw a new instance of the Error
object with the message "Cannot divide by zero"
. When we call the divide function with arguments 10
and 0
, it throws an error, and the program execution stops.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.