NiHaoLiHai
NiHaoLiHai

Reputation: 33

Javascript - throw not working in an error handling situation

I've been trying to define a function which checks whether a number is positive or not and I wanted to use "throw" but I didn't find a way to make it work using "throw". I trying using "throw" inside the "try" block as well but it didn't work either. So my question is...

Why does this work:

    function isPositive(a) {


    if (a < 0) {
        return 'Negative Number';
    }

    if (a == 0) {
        return 'Codename Error Zero'
    }

    try {
        return 'It IS a positive number!';
    }
    catch(e) {
        console.log(e);
    }
}

and this doesn't:

    function isPositive(a) {


    if (a < 0) {
        throw 'Negative Number';
    }

    if (a == 0) {
        throw 'Codename Error Zero'
    }

    try {
        return 'It IS a positive number!';
    }
    catch(e) {
        console.log(e);
    }

}

Thanks!

Upvotes: 0

Views: 3560

Answers (2)

Prince Hernandez
Prince Hernandez

Reputation: 3721

in order to make it work as similar as you want you need to wrap your ifs with the try

function isPositive(a) {
  try {
    if (a < 0) {
      throw 'Negative Number';
    }

    if (a == 0) {
      throw 'Codename Error Zero'
    }


    return 'It IS a positive number!';
  } catch (e) {
    console.log("we got an error");
    console.log(e);
  }

}

isPositive(0);

remember that a throw will stop the execution of the code that is after that throw, as an example:

as you can see, the code will stop in the first throw and the code after won't be executed, that is what is happening when you throw before your try

function test() {
  throw 'we throw ASAP'
  var x = 1;
  var y = 2;

  throw 'another error';
  throw x + y;

  return x + y;
}

test()

also remember that the control of the throw will be passed to the first catch block in the call stack. so when you put throw outside the try/catch your error was being handled by another try/catch

something to get familiar with throw could be this article: Throw - javascript | MDN

Upvotes: 1

Paalar
Paalar

Reputation: 265

The problem occurs due to how try .. catch works. Try catch will first, try to do what is inside the bracket (which is to return the It IS a positive number!), if returning the string fails (which it will not), it will log the error.

If you want to throw an error, and catch it, you need to do it inside of the try .. catch

Here's an example

try {
  throw "This wll fail";
} catch (e) {
  console.log(e);
}

Upvotes: 1

Related Questions