Open In App

JavaScript – throw not working in an error handling situation

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

In this article, we will try to understand in which case or how does throw statement doesn’t work in an error handling situation and how does or by which way possible we may correct it in order to produce the correct output with the help of certain examples in JavaScript.

Let us have a look over the below section that contains certain coding examples as well as their theoretical explanation in order to illustrate our problem statement as well as its solution in a much better and more efficient way.

Example 1:

  • In this example, we will try to cover our problem statement in as much detail as possible. 
  • Here we will take a random example, like checking whether a number is positive or not. 
  • For that, we will create a function that will accept an integer as its parameter and later will check that number’s value using multiple if-statements. 
  • According if the number is not positive (that is negative) or if the number is zero, we will be thrown random error messages one after the other. 
  • Later under try-block, we will return a line stating them, yes the number found out is positive in nature and if not then the thrown error will be cached inside the catch block itself.
  • Later at the end in output, we will see that the throw part is not displaying the error as we want in the expected output.

Javascript




<script>
    let checkNumberValue = (num) => {
        if (num < 0) {
            throw new Error(`${num} is a negative number`);
        }
  
        if (num === 0) {
            throw new Error(`${num} found...!!`);
        }
  
        try {
            return `${num} is a positive number`;
        } catch (error) {
            console.log(error);
        }
    };
  
    checkNumberValue(-5);
</script>


Output:

throw new Error(`${num} is a negative number`);
^
Error: -5 is a negative number
    at checkNumberValue (c:\Users\acer\Desktop\GeeksforGeeks Articles materials\varlet.js:1469:11)
    at Object.<anonymous> (c:\Users\acer\Desktop\GeeksforGeeks Articles materials\varlet.js:1483:1)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

As we have seen the output of this code snippet looks more ambiguous and more amount of unwanted or not required lines are coming in the output, so let’s look over the below-shown example which will show us the solution to the above-illustrated problem.

Example 2: 

  • In this example, we will take into the consideration previous example’s code’s function which was used to check the value of a passed number. 
  • Inside that function, we will put a try block at starting of the code itself and will use multiple if-statements in order to check whether the un-required facts are matching or not. 
  • If they are matching we will throw an error corresponding to them and later if not then we will return a statement stating that yes this number is a positive number. 
  • At last, we will catch all the errors which are thrown for certain cases inside the catch block itself.
  • In output now we will see that the throw statement is now working fine and the error message gets printed successfully as the desired output.

Javascript




<script>
    let checkNumberValue = (num) => {
        try {
            if (num < 0) {
                throw new Error(`${num} is a negative number`);
            }
  
            if (num === 0) {
                throw new Error(`${num} found...!!`);
            }
  
            return `${num} is a positive number`;
        } catch (error) {
            console.log("Caught Error: " + error.message);
        }
    };
  
    checkNumberValue(-5);
</script>


Output:

Caught Error: -5 is a negative number


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads