Try

Try Catch

JavaScript is a flexible language, but like any programming language, code can sometimes go wrong. That's where try...catch comes in. It helps you handle errors gracefully, without crashing your whole program. try...catch is used to run code that might fail and provide a fallback response if an exception is thrown. The syntax is a try block of code followed by a catch block and an optional finally block that runs regardless of an error.

try {
    // Code that may throw an error
} catch (error) {
    // Code to run if an error is caught
} finally {
    // Code that always runs, regardless of success or error
}

Errors

JavaScript has several built-in error types. Each serves a specific purpose.

Error Type Description
Error A generic error object (base class). Often used for custom errors.
EvalError Related to the eval() function and is rarely used.
RangeError A number is out of its allowable range (e.g. too many arguments).
SyntaxError Code has invalid syntax (e.g. a missing bracket).
TypeError A value is not of the expected type (e.g. calling something that isn't a function).
URIError Incorrect usage of URI functions like decodeURIComponent().

The syntax for catching these is to use the instanceof keyword. Typically you would use catch(err) to catch the errors and then repeat “err” in your code block. This is just by convention, but make sure that whatever is the in the catch() parentheses matches your calling of it in the following codeblock.

try {
    // Code that might throw an error
} catch (err) {
    if (err instanceof TypeError) {
        console.error("TypeError caught:", err.message);
    } else if (err instanceof SyntaxError) {
        console.error("SyntaxError caught:", err.message);
    } else if (err instanceof RangeError) {
        console.error("RangeError caught:", err.message);
    } else if (err instanceof EvalError) {
        console.error("EvalError caught:", err.message);
    } else if (err instanceof URIError) {
        console.error("URIError caught:", err.message);
    } else {
        console.error("Generic Error caught:", err.message);
    }
}

Throw

You can create your own errors in JavaScript using the throw keyword.

function divide(a, b) {
    if (b === 0) {
        throw new Error("Division by zero is not allowed.");
    }
    return a / b;
}

try {
    console.log(divide(5, 0));
} catch (err) {
    console.warn(err.message);
}