Open In App

Why we cannot catch error outside of function in JavaScript ?

Last Updated : 01 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • In this example, we will create a function that will accept an integer parameter value, which will be utilized further in the function.
  • Inside the function, we will try to create a try-catch block along with the finally (its result will be printed irrespective of any error being caught in function). 
  • Then, inside the try-block, we will check the integer value, and later in the catch block, we will catch the error caught in the try block after checking the integer value. Along with this,  in the catch block, we will throw another error inside it and that error we will catch later.
  • In the finally block, we will print a statement (in the form of a string) in console.log() & then return the integer parameter using the return statement. 
  • Then, we will make another function in which we will catch the error caught in the previously created function using the same try/catch block created in the previous function as well.

Javascript




<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:

  • The reason for the failure of the catch block, not being able to catch the error caught in the previous function’s try block, is the declaration of return statement being passed inside the finally block itself. 
  • This return statement will actually take the precedence order of executing the task and alters the result with which we as users won’t be able to receive or catch the error caught previously. 
  • In order to catch the error, we must not have to use any return statement in the finally block, and we will show it in the form of another example which is shown below.

Example 2: 

  • In this example, we will utilize the concept of the previous example, which includes the function’s declarations followed by the creation of try/catch block as well as finally block and so on.
  • Here, we will implement what we will avoid here using the return statement inside the finally block in order to make our error cached properly.
  • Instead of using a return statement, we will pass the returned data in the console.log() statement and the rest of the thing remains the same as what we have done in the previous example.
  • Here, we will successfully catch the error and will also be able to print that in the output itself.

Javascript




<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...!!


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads