# How to catch exceptions in setTimeout and setInterval

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Apr 5, 2021, updated Sep 24, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-catch-exception-inside-settimeout-setinterval

> A short guide to learning how to properly handle exceptions in JavaScript setTimeout and setInterval functions.

In JavaScript, we use the `try...catch` statement to capture unexpected errors and exceptions.

## How does `try...catch` work?

```javascript
try {
    // block of code
} catch (error) {
    // handle the error
} finally {
    // execute in all cases
}
```

1. The `try` clause is executed first.
2. If no exception is thrown, the `catch` clause is ignored, and the execution of the `try` statement is completed.
3. If an exception is thrown during the execution of the `try` clause, the rest of this clause is ignored. The `catch` clause is executed, and what comes after the `try` statement is executed.
4. The `finally` clause is optional and executes after both clauses, regardless of whether an exception is thrown or not.

## Capturing 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:

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

![Uncaught Exception Example](https://statics.attacomsian.com/gims/11da3e3b-f7b8-4682-9bbe-1b39fb3df286.png)

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

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

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

![Caught Exception Example](https://statics.attacomsian.com/gims/a2917934-4de4-4db4-9d9d-3256397e043f.png)
