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

标签 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" 

undefined 

有什么建议为什么我的代码与输出一起打印未定义吗?提前致谢。

最佳答案

这是因为如果 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));

关于javascript - 为什么我的 JavaScript 代码打印未定义并抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55350980/

相关文章:

python - 浏览 psutil 警告滚动控制台

javascript - 在 CKEditor 中保留 SCRIPT 标签(以及更多)

PHP: 'or' 指令失败语句:如何抛出新异常?

javascript - 从链接的输入字段中删除文本时删除 NaN

c# - 终止应用程序时导致的 System.Runtime.InteropServices.COMException

javascript - react native ListView 项目 ZIndex

javascript - 如何显示在父级下排列的 div 以进行树链接显示

ios - UITableViewCell 内的 UICollectionView 断言失败

javascript - 如何在 JavaScript 中抛出 mouseEvent?

javascript - 使用 JQuery 根据鼠标位置定位 <b> 标签