JavaScript: try...catch
The try...catch statement lets code handle an exception and recover or report a useful failure.
What you will learn
- How a try block and catch block work
- When finally is useful for cleanup
- How to report errors without hiding their cause
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
- Do not use an empty catch block; it makes failures invisible.
- Do not show raw stack traces or sensitive details to users; log safely and display a useful message.
- Catch errors you can handle, and let unexpected failures reach appropriate monitoring.