Open In App

JavaScript – throw not working in an error handling situation

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:




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




<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

Article Tags :