Open In App

Is it possible to retry a try-catch block if error is thrown in JavaScript ?

In this article, we will try to understand how we retry a try/catch block if any particular error is thrown in JavaScript with the help of theoretical as well as coding examples as well.

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.



Example 1: 




<script>
    let checkNumber = (num) => {
        let random_number = Math.floor(Math.random() * 10);
 
        if (random_number === num) {
            return `Yes number ${random_number}
                matches with the passed in number ${num}`;
        } else {
            throw new Error("Number doesn't matches");
        }
    };
 
    try {
        console.log(checkNumber(6));
    } catch (error) {
        console.log(error.message);
    }
</script>

Output:



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.

Example 2: 




<script>
    let checkNumber = (num) => {
        let random_number = Math.floor(Math.random() * 10);
 
        if (random_number === num) {
            return `Yes number ${random_number} matches
                with the passed in number ${num}`;
        } else {
            throw new Error("Number doesn't matches");
        }
    };
 
    let checkAgainNumber = () => {
        while (true) {
            try {
                return checkNumber(7);
            } catch (error) { }
        }
    };
 
    console.log(checkAgainNumber());
</script>

Output:

Yes number 7 matches with the passed in number 7

Article Tags :