[英]Is there way to throw an exception from an expression besides using functions?
Is there a way to explicitly throw an exception from an expression in JavaScript besides placing that throw
a function wrapper? 除了放置
throw
函数包装的方法外,是否有办法从JavaScript表达式中显式引发异常?
throw
is a statement, statements don't produce values, thus they cannot be used in expressions which operate on values and always produce a value. throw
是一个语句,语句不产生值,因此不能在对值进行运算并始终产生值的表达式中使用它们。 It's quite obvious that any statement can be put to a function and a function call can be used from the expression. 很明显,任何语句都可以放在函数中,并且可以从表达式中使用函数调用。 Is there a way to avoid wrapping the
throw
statement to a function and throw from the expression directly? 有没有一种方法可以避免将
throw
语句包装到函数并直接从表达式中抛出?
UPDATE: 更新:
Some people say it's not quite clear what I am asking about. 有人说我在问什么不清楚。 Consider a hypothetical example (not for real), this is something I wish worked, but it doesn't:
考虑一个假设的例子(不是真实的例子),这是我希望起作用的东西,但它没有:
var one = value != null ? value * value : (throw new Error('The value has not been provided'));
var two = value != 0 ? 1 / value : (throw new Error('The result cannot be evaluated because the value is zero which would give a division by zero problem.));
No. As you say, throw
is a statement and statements cannot appear as parts of an expression. 否。正如您所说,
throw
是一个语句,语句不能作为表达式的一部分出现。
The only way to execute a statement from the evaluation of an expression are a function call or eval
. 从表达式求值执行语句的唯一方法是函数调用或
eval
。 Using a THROW(new Error(…))
function is probably the best you can get. 使用
THROW(new Error(…))
函数可能是最好的选择。
But seriosly, go with simple, readable statements: 但有趣的是,请使用简单易读的语句:
if (value == null) throw new Error('The value has not been provided');
var one = value * value;
if (value == 0) throw new Error('division by zero");
var two = 1 / value;
That will not only work, but also fit in a line. 这不仅行得通,而且还可以排成一行。
Yes you can throw from a ternary! 是的,你可以扔三元! Perhaps some might call my solution a bit of a hack, but it is very simple to reason about.
也许有些人可能将我的解决方案称为hack,但是推理起来很简单。
var two = value != 0 ? 1 / value : (void 0).throwDivideByZero()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.