为什么我的JavaScript代码在打印时未定义并抛出异常?

时间:2019-03-26 06:26:19

标签: javascript exception

这里的问题是,随着输出的到来,JavaScript也说未定义。我在w3schools.com和developers.mozilla网站上看到了一些代码,还尝试了其他一些网站,但是没有找到任何解决方案或对遇到的问题的任何解释。

我想在出现0或负值时引发异常。

function isPositive(a) {

  try {
    if (a > 0) return "YES";

    if (a < 0) throw "Negative Value";

    if (a == 0) throw "Zero Value";
  } catch (error) {
    console.log(error);
  }
}


console.log(isPositive(0));

预期输出为 "Zero Value"

实际输出为

"Zero Value" 

undefined 

有人建议为什么我的代码与输出一起输出未定义的内容?预先感谢。

2 个答案:

答案 0 :(得分:1)

这是因为如果在try中抛出任何错误,它不会停止执行代码。如果要在出错时停止该功能,只需删除该try-catch并简单地return

function isPositive(a){
    if(a>0) return "YES"
    if(a<0) return "Negative Value";
    if(a == 0) return "Zero Value";
}
console.log(isPositive(0));

如果您想引发错误,请将语句从try中删除

function isPositive(a){
    if(a>0) return "YES"
    if(a<0) throw ("Negative Value");
    if(a == 0) throw ("Zero Value");
}
console.log(isPositive(0));

答案 1 :(得分:0)

function isPositive(a){
try{
if(a>0) return "YES";

   if(a<0) throw "Negative Value";

   if(a == 0) throw "Zero Value";
}catch(err)
{
return err;
}
}


console.log(isPositive(0));

我找到了答案,此代码对我有用,并给出了适当的结果。