try... catch
Instead of halting the code execution, we can use the try...catch
construct that allows catching errors without dying the script. The try...catch
construct has two main blocks; try
and then catch
.
try {
// code...
} catch (err) {
// error handling
}
At first, the code in the try
block is executed. If no errors are encountered then it skips the catch
block. If an error occurs then the try
execution is stopped, moving the control sequence to the catch
block. The cause of the error is captured in err
variable.
try {
// code...
alert('Welcome to Learn JavaScript');
asdk; // error asdk variable is not defined
} catch (err) {
console.log("Error has occurred");
}
try...catch
works for runtime errors meaning that the code must be runnable and synchronous.
To throw a custom error, a throw
statement can be used. The error object, that gets generated by errors has two main properties.
- name: error name
- message: details about the error
If we don't need an error
message catch can be omitted.