Javascript:"throw undefined"安全吗?
Javascript: is it safe to "throw undefined"?
在下面的函数中,当条件失败时,我希望将该情况作为简单错误处理(无需详细信息)。出于好奇,写 throw undefined
可以安全吗?
function splitYearMonth (YM) { // Returns ["yyyy-mm", yyyy, mm]
try {
var o = YM.match(/^(\d{4})\-(0[1-9]|1[012])$/);
if (o != null) {
return [o[0], parseInt(o[1], 10), parseInt(o[2], 10)];
} else {
throw undefined;
}
} catch (e) {
return [undefined, undefined, undefined];
}
}
throw 的语法是:
throw expression;
因为 undefined
是一个有效的表达式,所以这样做是安全的,尽管 return 一个合理的错误消息通常是一个好习惯,例如:
throw "Failed to split year and month for the given input"
是的,这样做是安全的。
ECMAScript 5.1 规范says:
The production ThrowStatement : throw [no LineTerminator here]
Expression ; is evaluated as follows:
- Let exprRef be the result of evaluating Expression.
- Return (throw, GetValue(exprRef), empty).
ECMAScript 6 uses the same terms.
undefined
肯定是个表达式,所以可以抛。您可以在 this fiddle.
中查看示例
也就是说,从可维护性的角度来看,抛出 undefined
可能不是一个好主意,因为这样做会让您完全不知道异常原因。抛出一个字符串可以说是一个更好的解决方案:
var o = YM.match(/^(\d{4})\-(0[1-9]|1[012])$/);
if (o != null) {
return [o[0], parseInt(o[1], 10), parseInt(o[2], 10)];
} else {
throw "unrecognized date format";
}
更新: 仔细想想,除非你问题中的 不需要详细信息 条款意味着您没有告诉我们整个故事,您只需要控制流程,而不是异常处理。你只需要写:
function splitYearMonth(YM) { // Returns ["yyyy-mm", yyyy, mm]
var o = YM.match(/^(\d{4})\-(0[1-9]|1[012])$/);
if (o != null) {
return [o[0], parseInt(o[1], 10), parseInt(o[2], 10)];
} else {
return [undefined, undefined, undefined];
}
}
异常处理可能很昂贵,通常不建议将此工具用于控制流(因为我们讨论的是 Javascript 而不是 Python)。
在下面的函数中,当条件失败时,我希望将该情况作为简单错误处理(无需详细信息)。出于好奇,写 throw undefined
可以安全吗?
function splitYearMonth (YM) { // Returns ["yyyy-mm", yyyy, mm]
try {
var o = YM.match(/^(\d{4})\-(0[1-9]|1[012])$/);
if (o != null) {
return [o[0], parseInt(o[1], 10), parseInt(o[2], 10)];
} else {
throw undefined;
}
} catch (e) {
return [undefined, undefined, undefined];
}
}
throw 的语法是:
throw expression;
因为 undefined
是一个有效的表达式,所以这样做是安全的,尽管 return 一个合理的错误消息通常是一个好习惯,例如:
throw "Failed to split year and month for the given input"
是的,这样做是安全的。
ECMAScript 5.1 规范says:
The production ThrowStatement : throw [no LineTerminator here] Expression ; is evaluated as follows:
- Let exprRef be the result of evaluating Expression.
- Return (throw, GetValue(exprRef), empty).
ECMAScript 6 uses the same terms.
undefined
肯定是个表达式,所以可以抛。您可以在 this fiddle.
也就是说,从可维护性的角度来看,抛出 undefined
可能不是一个好主意,因为这样做会让您完全不知道异常原因。抛出一个字符串可以说是一个更好的解决方案:
var o = YM.match(/^(\d{4})\-(0[1-9]|1[012])$/);
if (o != null) {
return [o[0], parseInt(o[1], 10), parseInt(o[2], 10)];
} else {
throw "unrecognized date format";
}
更新: 仔细想想,除非你问题中的 不需要详细信息 条款意味着您没有告诉我们整个故事,您只需要控制流程,而不是异常处理。你只需要写:
function splitYearMonth(YM) { // Returns ["yyyy-mm", yyyy, mm]
var o = YM.match(/^(\d{4})\-(0[1-9]|1[012])$/);
if (o != null) {
return [o[0], parseInt(o[1], 10), parseInt(o[2], 10)];
} else {
return [undefined, undefined, undefined];
}
}
异常处理可能很昂贵,通常不建议将此工具用于控制流(因为我们讨论的是 Javascript 而不是 Python)。