Let us first have a look into the below-illustrated example which will help us to understand what will happen if don’t retry a try/catch block which further throws an error if a certain result condition doesn’t meet.
- In this example, we will create a function and inside that function, we will create a variable that will store a randomly generated number.
- After storing the random number, we will multiply the number by 10 and further will obtain the floor value of all that calculated stuff using another method called Math.floor() method.
- After doing all this stuff we will check whether that number matches with our passed-in number and accordingly we will either display the result or throw the error and later will catch it.
Number doesn't matches
As we have seen in the output as well as the code snippet, most of the time throw Error statement, and thus most of the time our passed-in number doesn’t matches with the randomly generated number. Let us have a look at the below-illustrated example which will create a re-try try/catch block until that passed in number matches with the randomly generated number inside that function.
- In this example, we will create another function and will take into consideration the function which we have created in the previous example itself.
- Inside that, another function under the while loop will create a try/catch block, and inside that try, block will return our first function so that if the number doesn’t match we may catch the error thrown by the first function inside that catch block.
- The output will surely here be a positive one which will state that “yes number matches with the passed-in number”, but here our call-stack size will be increased since multiple times error will be cached as number apart from one time gets rejected always.
Yes number 7 matches with the passed in number 7