Catching exceptions in setTimeout and setInterval

Errors and exceptions are among the problems encountered in any programming conceptions. By producing these errors, whether they are probable or not, we learn to better apprehend and anticipate them. In any case, we must make sure that our program works properly when faced with unexpected conditions. To handle errors/exceptions in JavaScript or even in other languages, we most often use try...catch.

How does try…catch work?

try {
  // code...
} catch (error) {
  // error handling
} finally {
  // executed in all cases
}
  • The try clause is executed.

  • If no exception is raised, the catch clause is ignored and the execution of the try instruction 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 instruction is executed.

The final clause is an optional clause of the try statement. At this level, the code will be always executed after both clauses, regardless of whether an exception has been thrown or not.

Note that it is possible to raise exceptions with the throw instruction

If an exception is thrown when using setTimeout or setInterval, the catch clause will not catch any of them, since try...catch works synchronously and the function in question will only be executed later. To fix this, it is necessary to put this block inside our function.

In this example the error is raised but not catched
try {
  setTimeout(() => {
    throw new Error("An exception is raised");
  }, 1000);
} catch (error) {
  console.error({ error });
}
In this example the error is raised and catched
setTimeout(() => {
  try {
    throw new Error("An exception is raised");
  } catch (error) {
    console.error({ error });
  }
}, 1000);

See also

Before you leave…
Thanks for reading! 😊