Open In App

Why we cannot catch error outside of function in JavaScript ?

In this article, we will try to understand why and how we wouldn’t be able to catch an error outside of the function, and later we will try to resolve this issue with the help of an example in JavaScript.

First, we will try to understand our problem statement more clearly with the help of an example, along with some theoretical explanations, which are shown below:



Example 1:




<script>
    let checkPassedValue = (num) => {
        try {
            if (num === 5) 
                console.log(`${num} found successfully..!!`);
            else 
                throw new Error(`${num} is not the required number`);
        } catch (error) {
            console.log(error.message);
            throw new Error("Error thrown in Catch Block...!!");
        } finally {
            console.log("Finally block's data content...");
            return num;
        }
    };
  
    let dataChecking = () => {
        try {
            let data = checkPassedValue(10);
            console.log("Data value received from "
                + "First Function is: " + data);
        } catch (error) {
            console.log("Catched error in next function is: "
                + error.message);
        }
    };
  
    dataChecking();
</script>

Output: In the output, as shown below, we will see that our error didn’t catch or cached properly from the first function to the second function.



10 is not the required number
Finally block's data content...
Data value received from First Function is: 10

Explanation:

Example 2: 




<script>
    let checkPassedValue = (num) => {
        try {
            if (num === 5) 
                console.log(`${num} found successfully..!!`);
            else 
                throw new Error(`${num} is not the required number`);
        } catch (error) {
            console.log(error.message);
            throw new Error("Error thrown in Catch Block...!!");
        } finally {
            console.log("Finally block's data content..." + num);
        }
    };
  
    let dataChecking = () => {
        try {
            let data = checkPassedValue(10);
            console.log("Data value received from "
                + "First Function is: " + data);
        } catch (error) {
            console.log("Catched error in next function is: "
                + error.message);
        }
    };
  
    dataChecking();
</script>

Output:

10 is not the required number
Finally block's data content...10
Catched error in next function is: Error thrown in Catch Block...!!

Article Tags :