Errors and exceptions are common in all programming languages. In JavaScript, we use the try...catch statement to capture unexpected errors and exceptions.

How does try...catch work?

try {
    // block of code
} catch (error) {
    // handle the error
} finally {
    // execute in all cases
}
  • The try clause is executed first.
  • If no exception is thrown, the catch clause is ignored and the execution of the try statement is completed.
  • If an exception is raised during the execution of the try clause, the rest of this clause is ignored. The catch clause is executed, and then what comes after the try statement is executed.
  • The finally clause is optional and executes after both clauses, regardless of whether an exception has been raised or not.

Handling exceptions in setTimeout and setInterval

Both setTimeout and setInterval functions call or evaluate an expression after a specified number of milliseconds. If we put these methods inside the try clause and an exception is thrown, the catch clause will not catch any of them:

try {
    setTimeout(() => {
        throw new Error(`An exception is thrown`);
    }, 500);
} catch (error) {
    console.error({ error });
}

Uncaught Exception Example

This is because the try...catch statement works synchronously, and the function in question is executed asynchronously after a certain amount of time.

To resolve this issue, we have to put the try...catch block inside the function:

setTimeout(() => {
    try {
        throw new Error(`An exception is thrown`);
    } catch (error) {
        console.error({ error });
    }
}, 500);

Caught Exception Example

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.