Skip to content
Amal Hashim
All posts
Snippet

JavaScript error handling

Handle exceptions in JavaScript with try, catch and finally, and catch everything else with window.onerror.

1 min read#JavaScript

There are two ways to handle errors in JavaScript.

try, catch, finally

Wrap code that might fail in a try block. The finally block always runs.

js
try {
    // Code block
}
catch (e) {
    // Handle exception
}
finally {
    // Always runs
}

window.onerror

Use window.onerror as a generic handler for errors that nothing else caught.

js
window.onerror = function (error, fileName, lineNumber) {
    // Handle exception
};