Eliminate incomplete execution of a set of functions due to unforeseen errors

In this article, we will try to understand how we may eliminate incomplete execution of a set of functions due to unforeseen errors with the help of a coding example in JavaScript.
Let us first understand how we may throw as well as catch an error inside a function itself with the help of the following enlightened section that shows the exact syntax which is to use for the same:
Syntax: The following syntax, we may use in order to throw an error in a function, later catch that error in the same function itself (Note here we have used arrow function, the user could also opt for normal function declaration syntax as well):
let function_name = () => {
try {
// error_message is the string value
throw new Error(error_message);
}
catch(error) {
// Do something with this error
}
}
Let us have a look over the following shown example that will help us to understand the above enlightened syntax in a much better and more efficient manner.
Example 1: In this example, we will simply create a function (preferably an arrow function) and inside that, we will create a try/catch block, and then in the try block itself we will throw an error and then catch that error in catch block itself.
Javascript
<script> let errorMethod = () => { try { throw new Error("Please try again later..!"); } catch (error) { console.log(error.message); } }; errorMethod(); </script> |
Output:
Please try again later..!
Now let us understand our main task which is how to eliminate incomplete execution of a set of functions due to unforeseen errors with a coding example which is enlightened below:
Example 2: In this example, we will create multiple functions which will throw their own respective errors which we will catch in other methods forming a chain of method execution.
Javascript
<script> let firstErrorFunction = () => { try { throw new Error( "Error thrown by First Function...!!"); } catch (error) { console.log("Catched error in First Function: " + error.message); throw new Error( "Another error thrown by first function...!!"); } }; let secondErrorFunction = () => { try { firstErrorFunction(); } catch (error) { console.log("Catched error in Second Function: " + error.message); throw new Error( "Error thrown by second function...!!"); } }; let thirdErrorFunction = () => { try { secondErrorFunction(); } catch (error) { console.log("Catched error in Third Function: " + error.message); } console.log("No more errors are left for catching..."); }; thirdErrorFunction(); </script> |
Output:
Catched error in First Function: Error thrown by First Function…!!
Catched error in Second Function: Another error thrown by first function…!!
Catched error in Third Function: Error thrown by second function…!!
No more errors are left for catching…



