No matter how great we are at programming, sometimes our scripts have errors. They may occur because of our mistakes, an unexpected user input, an erroneous server response, and for a thousand other reasons.
Usually, a script “dies” (immediately stops) in case of an error, printing it to console.
But there’s a syntax construct try...catch that allows us to “catch” errors so the script can, instead of dying, do something more reasonable.
The “try…catch” syntax
The try...catch construct has two main blocks: try, and then catch:
try {
// code...
} catch (err) {
// error handling
}
It works like this:
- First, the code in
try {...}is executed. - If there were no errors, then
catch (err)is ignored: the execution reaches the end oftryand goes on, skippingcatch. - If an error occurs, then the
tryexecution is stopped, and control flows to the beginning ofcatch (err). Theerrvariable (we can use any name for it) will contain an error object with details about what happened.