assert(false)vs RuntimeException? [英] assert(false) vs RuntimeException?
问题描述
我正在阅读 XWalkUIClientInternal ,我遇到了以下代码:
I'm reading the source of XWalkUIClientInternal and I ran into the following code:
switch(type) {
case JAVASCRIPT_ALERT:
return onJsAlert(view, url, message, result);
case JAVASCRIPT_CONFIRM:
return onJsConfirm(view, url, message, result);
case JAVASCRIPT_PROMPT:
return onJsPrompt(view, url, message, defaultValue, result);
case JAVASCRIPT_BEFOREUNLOAD:
// Reuse onJsConfirm to show the dialog.
return onJsConfirm(view, url, message, result);
default:
break;
}
assert(false);
return false;
我从来没有真正看到这种技术,也没有真正考虑过,但我猜这本质上是这是不可达到的代码,不应该发生,无论什么都崩溃了。虽然技术上你可以做一个Throwable,只要它没有被捕获。
I've never really seen this technique nor really thought about it before, but I guess this essentially means "this is unreachable code and should not happen ever", and crash the app no matter what. Although technically you can do that with a Throwable, as long as it's not caught.
所以我的问题是,哪一个更好,为什么, assert(false)
或抛出一个 RuntimeException
,或者可能是一个错误
?
So my question is, which one is better and why, assert(false)
or throwing a RuntimeException
, or maybe an Error
?
推荐答案
assert false;
(不需要括号,断言
不是一个函数,而是一个语句。)和
(The parenthesis are not needed, assert
is not a function but a statement.) and
throw new RuntimeException();
是断言可以被禁用。实际上,除非JVM以 -ea
(enable assertions)标志开始,否则 将被禁用。如果断言被启用, assert false
将无条件地抛出一个 AssertionError
,它来源于错误
。但是,由于断言可以被禁用,所以有两个问题,
is that the assertion can be disabled. Actually, it is disabled by default unless the JVM is started with the -ea
("enable assertions") flag. If assertions are enabled, assert false
will unconditionally throw an AssertionError
which derives from Error
. But since assertions can be disabled, there are two problems,
- 错误可能未被检测到,
- 断言(这主要是混乱的)之后的一个虚拟的
返回
语句。
- the error might go undetected and
- control flow analysis requires a dummy
return
statement after theassert
(which is mostly clutter).
因此,在上述情况下,我一定会明确(而且更简洁)
Therefore, in the above case, I'd certainly go with an explicit (and more concise)
throw new AssertionError("invalid type " + type);
而不是一个断言
返回
。
如评论中所述,这是假设类型
是内部参数,无效值表示逻辑本身的错误。如果它是一个输入参数,它应该根据通常的规则进行验证,并且 IllegalArgumentException
如果验证失败,则抛出
As mentioned in the comments, this is assuming that type
is an internal parameter and an invalid value indicates a bug in the logic itself. If it is an input parameter, it should be validated according to the usual rules and an IllegalArgumentException
be thrown if validation fails.
这篇关于assert(false)vs RuntimeException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!