繁体   English   中英

“throw”语句的意外“未定义”输出

[英]Unexpected 'undefined' output from 'throw' statement

我编写了一个简单的函数来检查传递的参数是 0、正数还是负数。 我知道一个事实,即传递的参数是一个数字,而不是任何其他数据类型。 我将undefined作为输出,而我希望在传递的参数为零或负数的情况下打印 throw 语句中提供的文本。

  1. 我已经在 JavaScript中的Throw 语句中检查了问题给出了 "undefined undefined" output ,但这并不能解决我的问题。

  2. 我还尝试定义一个 Error 对象,如下所示:

     ZeroError = new Error ("Zero Error"); NegativeError = new Error ("Negative Error");

然后使用这些错误作为参数来“抛出”:

throw ZeroError;

throw NegativeError;

对于零值和负值,我得到相同的undefined输出。

这是我的功能:

function isPositive(a)
{
    if (a === 0) throw "Zero Error";
    if (a < 0) throw "Negative Error";
    if (a > 0) return ("YES");
}

当 a > 0 时我得到“YES”作为输出,当 a 为零或负数时我得到undefined 当 a 为零时,我期望“零错误”,当 a 为负时,我期望“负错误”。

throw不返回任何东西,它抛出一个异常,用return替换它,你就会得到你的价值。

throw 语句抛出用户定义的异常。 当前函数的执行将停止(不会执行 throw 之后的语句),并将控制权传递给调用堆栈中的第一个 catch 块。 如果调用者函数之间不存在 catch 块,则程序将终止。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw

编辑:如果您需要捕获异常,请查看try/catchhttps : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

function isPositive(a) {
    if (a === 0) throw "Zero Error";
    if (a < 0) throw "Negative Error";
    if (a > 0) return ("YES");
}

let result; 
try {
   result = isPositive(0);
} catch (e) {
   if (e === "Zero Error") result = "Zero Error";
   if (e === "Negative Error") result = "Negative Error";
}

问题的优化解决方案。 我希望每个人都清楚:)

function isPositive(a) {
    try {
        if (a == 0) throw 'Zero Error';
        if (a < 0) throw 'Negative Error';
        return 'YES';
    } catch (throwedErrorMessage) {
        return throwedErrorMessage;
    }
}
function Positive(a)
{
  try { 
    if (a === 0)
      throw "Zero Error";
    if (a < 0) throw "Negative Error";
    if (a > 0) return ("YES");
    document.write("hello")
  }
  catch(err) {
   document.write("hello");
}
}
Positive();

这有效:

function isPositive(a) {
    try {
        if (a < 0) {
            throw "Negative Error"
        } else
            if (a == 0) {
                throw "Zero Error";
            } else {
                return "YES"
            }
    }
    catch (err) {
        return err;
    }
}
  1. 需要尝试捕获
  2. 从 catch 返回错误很重要。 错误的返回将解决“未定义”的返回。

这对我来说非常有效:

function isPositive(a) {
    if(a>0) {
        return 'YES';
    }
    if (a===0) {
        throw new Error("Zero Error");
    }
    else if (a<0) {
        throw new Error("Negative Error");
    }
}

不确定使用 throw 有什么问题,就是这样。 稍后当我找到真正的原因时,我会在这里添加它。

https://humanwhocodes.com/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM