Language: EN

excepciones-en-javascript

How to Use Exceptions in JavaScript

Exceptions are events that occur during the execution of a program that interrupt its normal flow (usually represents an error that occurred in the program).

When an exception is thrown, the normal execution of the 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-catch block
  • If not, it passes to the function that invoked the one that generated the error

If not handled, the program stops 💥

Exception Handling

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
  • This will be handled in the catch block.

Types of Errors

JavaScript classifies errors into several categories, each with specific characteristics and causes. The main types of errors are:

Error TypeDescription
ErrorGeneric error, the base class for all exceptions.
TypeErrorOccurs when an operation is performed on an inappropriate type.
RangeErrorThrown when a value is outside the allowed range.
ReferenceErrorOccurs when trying to access an undefined variable.
SyntaxErrorThrown for syntax errors in JavaScript code.
URIErrorOccurs when using URI encoding functions with a malformed URI.
EvalErrorThrown in situations of incorrect use of the eval() function.

Error Examples

SyntaxError

The code will generate a SyntaxError due to a missing closing parenthesis.

let x = 10;
console.log(x;

ReferenceError

console.log(nonExistentVariable);

This code will throw a ReferenceError because nonExistentVariable is not defined.

TypeError

Here, TypeError occurs because toUpperCase is not defined for the Number type.

let num = 123;
num.toUpperCase(); // `toUpperCase` is not a valid method for numbers

RangeError

The previous code will generate a RangeError due to an invalid array size.

let arr = new Array(-1); // Cannot create an array with negative size

Creating Custom Exceptions

In addition to throwing standard exceptions, we can create our own custom exceptions. This serves to provide more specific information about errors in your application.

To create a custom exception, you can extend the Error class in JavaScript:

class MyException extends Error {
    constructor(message) {
        super(message);
        this.name = "MyException"; // Sets the name of the exception
    }
}

Let’s see it in 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,

  • MyException is used to throw a specific error related to name validation