我一直在尝试定义一个检查数字是否为正的函数,我想使用“ throw”,但是我没有找到一种使“ throw”起作用的方法。我也尝试在“ try”块中使用“ throw”,但是它也不起作用。所以我的问题是...
为什么这样做:
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);
}
}
这不是:
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);
}
}
谢谢!
答案 0 :(得分:1)
由于try .. catch
的工作方式而出现问题。首先尝试catch,尝试做括号内的操作(返回It IS a positive number!
),如果返回字符串失败(不会返回),则会记录错误。
如果您想引发错误并抓住它,则需要在try .. catch
内进行操作
这是一个例子
try {
throw "This wll fail";
} catch (e) {
console.log(e);
}
答案 1 :(得分:1)
为了使它像您希望的那样工作,您需要用ifs
包裹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);
请记住,例如,抛出将停止执行该抛出之后的代码:
如您所见,代码将在第一次抛出时停止,而之后的代码将不被执行,这就是您在try
之前抛出代码时发生的情况
function test() {
throw 'we throw ASAP'
var x = 1;
var y = 2;
throw 'another error';
throw x + y;
return x + y;
}
test()
还请记住,throw
的控件将被传递到调用堆栈中的第一个catch块。因此,当您将throw
放在try/catch
之外时,您的错误正在由另一个try/catch
可能与此文章类似的内容: Throw - javascript | MDN