Language: EN

como-usar-try-catch-en-javascript

Try Catch in JavaScript

The try...catch block is used to catch exceptions that may occur during the execution of code in JavaScript.

It allows us to manage errors that occur during execution, without interrupting the overall flow of the program (handling it in a controlled manner).

The basic syntax of try...catch is as follows:

try {
    // Code that may throw an error
} catch (error) {
    // Code that runs if an error occurs
} finally {
    // Code that always runs, regardless of whether an error occurred or not
}
  • try: Contains the block of code that you want to execute and that could throw an exception.
  • catch: Catches the exception thrown in the try block and allows you to handle the error.
  • finally (optional): Contains code that always runs, whether an error occurred or not.

How to use try…catch

Let’s look at a simple example to understand how try...catch works:

try {
  let undefinedVar; // Not initialized

// This will throw a TypeError
  console.log(undefinedVar.toString()); 
} catch (error) {
  console.log("Captured error:", error.message);
}

// would show
// Captured error: Cannot read properties of undefined (reading 'toString')

In this example, the TypeError is caught and handled in the catch block.

Handling errors

Next, an example where an error is intentionally thrown:

function getElement(arr, index) {
    try {
        if (index < 0 || index >= arr.length) {
            throw new Error("Index out of bounds");
        }
        return arr[index];
    } catch (error) {
        console.error("Error:", error.message);
    }
}

const numbers = [1, 2, 3];
console.log(getElement(numbers, 5)); // Error: Index out of bounds

In this case, an error is thrown if attempting to access an index that does not exist in the array. The catch block catches the error and displays a message in the console.

Using finally

The finally block is optional and is used to execute code that should always run (regardless of whether an error occurs or not).

try {
	let undefinedVar; // Not initialized

	// This will throw a TypeError
	console.log(undefinedVar.toString()); 
} catch (error) {
	console.log("Captured error:", error.message);
} finally {
	console.log("This will always be printed");
}

// would show:
// Captured error: Cannot read properties of undefined (reading 'toString')
// This will always be printed

In this case, regardless of whether an error occurs, the message “This will always be printed” will always be displayed.

Specific error handling

Sometimes it is useful to distinguish the type of errors we have caught. For this, we can use instanceof within the catch block.

try {
  // Code that may fail
} catch (error) {
  if (error instanceof TypeError) {
    console.log("Type of error:", error.message);
  } else {
    console.log("Other type of error:", error.message);
  }
}