try...catch
Catches errors so the program does not stop.
Available since: ES3
Syntax
try { … } catch (error) { … } finally { … }Examples
An error does not stop the program:
try {
JSON.parse('not JSON');
console.log('not printed');
} catch (error) {
console.log('Could not parse:', error.name);
}
console.log('The program goes on');Output:
Could not parse: SyntaxError
The program goes onThe finally block always runs:
function load() {
try {
return 'data';
} finally {
console.log('cleanup');
}
}
console.log(load());Output:
cleanup
dataThe error variable can be omitted:
function isJson(text) {
try {
JSON.parse(text);
return true;
} catch {
return false;
}
}
console.log(isJson('[1, 2]'), isJson('[1, 2'));Output:
true falseNotes
try...catch only catches errors from synchronous code and await. It will not catch an error inside setTimeout or a promise without await.
Do not catch errors just in case and do not leave catch empty: real problems become invisible that way.
See also
- throw — Throws an error and stops the function.
- Error — The base error class: created and thrown with throw.
- Promise.prototype.catch — Handles a promise's error.
Related recipes
In the tutorial
- Errors and try...catch — Error handling in JavaScript: try, catch and finally blocks, the error object, the throw statement and built-in error types.