A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript-error-and-exceptional-handling-with-examples/ below:

Javascript Error and Exceptional Handling

Javascript Error and Exceptional Handling

Last Updated : 11 Jul, 2025

In JavaScript, error and exception handling allows you to manage unexpected issues that occur during the execution of your code. By using tools like try, catch, throw, and finally, you can handle errors easily and prevent the program from crashing. This enables you to provide meaningful error messages, debug your code efficiently, and maintain smooth execution.

What is JavaScript Error?

In JavaScript, an error is a problem that prevents the code from running as expected. Errors can occur during development or while the application is running, causing the program to stop executing properly. There are different types of errors in JavaScript.

Types of Errors in JavaScript JavaScript
console.log("Hello World" 
// Missing closing parenthesis

Output

SyntaxError: missing ) after argument list
JavaScript
console.log(x); // ReferenceError: x is not defined

Output

ReferenceError: x is not defined
JavaScript
let num = 5;
num.toUpperCase(); // TypeError: num.toUpperCase is not a function

Output

TypeError: num.toUpperCase is not a function
JavaScript
let arr = Array(-1); // RangeError: Invalid array length

Output

RangeError: Invalid array length
JavaScript
throw new Error("Custom error occurred");

Output

Error: Custom error occurred
Exception Handling in JavaScript

Exception handling in JavaScript refers to the process of dealing with errors (exceptions) that occur during the execution of a program. JavaScript provides some mechanisms to catch, handle, and recover from error instead of letting the error stop the program. The most common approach is using try...catch blocks.

Handling Errors Using try...catch

The try...catch statement

Syntax

try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
} finally {
// Optional: Code that runs regardless of success or error
}

Example

JavaScript
try {
    let res = 10 / 0;
    if (!isFinite(res)) {
        throw new Error("Cannot divide by zero");
    }
    console.log(res);
} catch (error) {
    console.error("Error occurred:", error.message);
} finally {
    console.log("Execution completed");
}

Output

Error occurred: Cannot divide by zero
Execution completed

In this example

Throwing Custom Errors

Sometimes, the standard JavaScript errors are not sufficient for our application needs. In such cases, you can throw custom errors using the throw statement.

JavaScript
function check(age) {
    if (age < 18) {
        throw new Error("Age must be 18 or above");
    }
    console.log("Access granted");
}
try {
    check(16);
} catch (error) {
    console.error(error.message);
    // Age must be 18 or above
}

Output

Age must be 18 or above

In this example

Using Finally for Cleanup

The final block is executed regardless of whether an error occurred or not.

JavaScript
try {
    console.log("Trying...");
    throw new Error("An error occurred");
} catch (error) {
    console.error(error.message);
} finally {
    console.log("Cleaning up...");
}

Output

Trying...
An error occurred
Cleaning up...

In this example

Advanced: try...catch with async/await JavaScript
async function fetchData() {
    try {
        let res = await fetch("https://api.example.com/data");
        let d = await res.json();
        console.log(d);
    } catch (error) {
        console.error("Error fetching data:", error.message);
    }
}
fetchData();

Output:

Error fetching data: fetch failed

In this example

Benefits of Exception Handling Best Practices for Error Handling

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4