[英]Javascript: is it safe to “throw undefined”?
In the function below, when the condition fails I want the situation to be handled as a simple error (no details needed). 在下面的函数中,当条件失败时,我希望将情境作为一个简单的错误处理(不需要任何细节)。 Just out of curiosity, is it OK and safe to write
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];
}
}
Yes, it is safe to do so. 是的,这样做是安全的。
The ECMAScript 5.1 specification says : ECMAScript 5.1规范说 :
The production ThrowStatement : throw [no LineTerminator here] Expression ;
生产ThrowStatement : 抛出 [此处没有LineTerminator ] 表达式; is evaluated as follows:
评估如下:
- Let exprRef be the result of evaluating Expression .
设exprRef是评估Expression的结果。
- Return (throw, GetValue( exprRef ), empty).
返回(throw,GetValue( exprRef ),为空)。
ECMAScript 6 uses the same terms . ECMAScript 6 使用相同的术语 。
undefined
is definitely an expression, so it can be thrown. undefined
绝对是一个表达式,所以它可以被抛出。 You can see an example in this fiddle . 你可以在这个小提琴中看到一个例子。
That said, throwing undefined
may not be a good idea from a maintainability standpoint, because doing so leaves you with no information at all about the cause of the exception. 也就是说,从可维护性的角度来看,抛出
undefined
可能不是一个好主意,因为这样做会让你完全没有关于异常原因的信息。 Throwing a string would arguably be a better solution: 抛出一个字符串可以说是一个更好的解决方案:
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";
}
Update: On second thought, unless the no details needed clause in your question means you're not telling us the whole story, you only need control flow, not exception handling. 更新:第二个想法,除非你的问题中没有需要细节的条款意味着你没有告诉我们整个故事,你只需要控制流程,而不是异常处理。 You only have to write:
你只需要写:
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];
}
}
Exception handling can be expensive, and it is usually not recommended to use this facility for control flow (since we're discussing Javascript and not, say, Python). 异常处理可能很昂贵,并且通常不建议将此工具用于控制流(因为我们讨论的是Javascript而不是Python)。
The syntax of throw is: throw的语法是:
throw expression;
As undefined
is a valid expression, it is safe to do this, although it is generally good practice to return a sensible error message, for example: 由于
undefined
是一个有效的表达式,所以这样做是安全的,尽管返回一个合理的错误消息通常是一种好习惯,例如:
throw "Failed to split year and month for the given input"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.