JavaScript: try...catch

The try...catch statement lets code handle an exception and recover or report a useful failure.

What you will learn

Minimal example

try {
  const data = JSON.parse(text);
  showResult(data);
} catch (error) {
  console.error(error);
  showMessage('The data could not be read.');
} finally {
  hideLoadingIndicator();
}

The catch block runs when code in try throws. finally runs whether the operation succeeds or fails, so it is useful for cleanup.

Common mistakes