JavaScript Error Handling (Try-Catch)
Ensure your web applications don't break unexpectedly. Learn how to handle errors safely using try, catch, and finally.
Handling Exceptions
No matter how great you are at programming, sometimes your scripts have errors. They may occur because of our mistakes, an unexpected user input, an erroneous server response, and for a thousand other reasons.
The try...catch syntax
The try...catch construct allows us to catch errors so the script can, instead of dying, do something more reasonable.
try {
// Code that may throw an error
let data = JSON.parse("{ bad json }");
} catch (err) {
// Error handling code
console.log("An error occurred: " + err.message);
}The finally clause
The try...catch construct may have one more code clause: finally. If it exists, it runs in all cases: after try (if there were no errors) and after catch (if there were errors).
Throwing Custom Errors
We can generate our own errors using the throw operator. Technically, we can throw anything, but usually we throw an Error object.
let age = 15;
try {
if(age < 18) {
throw new SyntaxError("User must be 18 or older.");
}
} catch (err) {
console.error(err.name); // SyntaxError
}