As a developer, we deal with lots of bugs and errors most of the time. As a result, in this article, we would explore the JavaScript try/catch/finally statement. I will explain what it does and how it can be used to handle errors in your code.
What are errors?
Errors are an integral aspect of programming. JavaScript errors can occur while writing code due to syntax issues such as missing or mistyped variables, duplicate variables, incorrect use of JavaScript constructs, and so on. They can also occur during runtime due to internal server errors, unreachable resources at an API endpoint, broken or missing data structures - whose interfaces are typically manipulated by our program, and so on.
So, when an error is expected, it is critical to handle errors gracefully and direct the flow of the program to a safe avenue where further execution can resume uninterrupted.
Graceful error handling
Graceful error handling is a programming approach in which we proactively consider the scenarios that could result in an error, design our control flow to handle these possible errors, and direct the control of the program in each case so that execution persists.
In Javascript, we use try/catch/finally
to handle the errors.
How try/catch/finally work?
try {
// things to be executed
} catch (error) {
// what to do when encountering an error
} finally {
// to be executed regardless of the try result
}
For example,
const a = 4;
const b = 4;
try {
// things to be executed
console.log(a / b)
} catch (error) {
// what to do when encountering an error
console.log('An error caught');
console.log('Error message: ' + error);
} finally {
// irrespective of try/catch, this function executes after try/catch is executed
console.log("Finally has been executed")
}
Conclusion
In this article, we have learned about try/catch/finally
to gracefully handle errors.
Thanks for reading
Follow me on Twitter
Thanks for reading!