Exceptions are events that occur during the execution of a program that interrupt its normal flow (generally representing an error that occurred in the program).
When an exception is thrown, the execution of the normal code is interrupted and control is transferred to the nearest exception handler (try…catch), if it exists.
That is, when an Exception occurs, it can:
- Be caught by a
try-catchblock - If not, it passes to the function that called the one that generated the error
If it is not handled, the program stops 💥
Throwing Exceptions
We can throw exceptions in JavaScript using the throw keyword. This allows us to indicate that an error has occurred and provide additional information about it.
The syntax is as follows:
throw new Error("Error message");
Let’s see a simple example:
function validateAge(age) {
if (age < 18) {
throw new Error("Age must be at least 18 years.");
}
return "Valid age";
}
try {
console.log(validateAge(15));
} catch (error) {
console.error("An error occurred:", error.message);
}
In this case,
- If an age less than 18 is passed, an exception will be thrown
- It will be handled in the
catchblock.
Creating Custom Exceptions
In addition to throwing standard exceptions, we can create our own custom exceptions. This is useful to provide more specific information about errors in your application.
To create a custom exception, you can extend JavaScript’s Error class:
class MyException extends Error {
constructor(message) {
super(message);
this.name = "MyException"; // Sets the name of the exception
}
}
Let’s see an example of how to use a custom exception:
function validateName(name) {
if (typeof name !== 'string' || name.length === 0) {
throw new MyException("Name must be a non-empty string.");
}
return "Valid name";
}
try {
console.log(validateName("")); // Will throw an exception
} catch (error) {
console.error(`${error.name}: ${error.message}`);
}
In this case,
MyExceptionis used to throw a specific error related to name validation
