Try...catch
Syntax
try {
// Code
}
catch (err) {
// Error handling
}
finally {
// Excuted always, regardless if there is any error. And is always last
}
Keep in mind that try...catch
works synchronously, so if you have asynchronous code and it throws an error after the execution of the try...catch
block, then the error will not be caught.
In order to catch some exception in an asynchronous code, the try...catch
must be inside the asynchronous function.
Error object
After an error has occurred inside the try...catch
object, JavaScript generates an object containing the details about it
name
: Name of the error that has occurredmessage
: Textual message about error detailsstack
: The current call stack
By default, if you print the err
object, it will print all three of these information, name, message, and stack
.
Throwing our own errors
We can use the throw
operator to generate our own error.
Technically we can throw anything as the error object, like primitives, numbers or strings, but is better if you throw an object.
let error = new Error(message);
try {
throw error;
}
catch (err) {
console.log(err);
}
There are many built-in constructors for standard errors: Error
, SyntaxError
, ReferenceError