断言(假)与运行时异常? [英] assert(false) vs RuntimeException?

查看:37
本文介绍了断言(假)与运行时异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 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,或者可能是 Error?

So my question is, which one is better and why, assert(false) or throwing a RuntimeException, or maybe an Error?

推荐答案

最大的区别

assert false;

(不需要括号,assert 不是函数而是语句.)和

(The parenthesis are not needed, assert is not a function but a statement.) and

throw new RuntimeException();

是可以禁用断言.实际上,除非 JVM 以 -ea(启用断言")标志启动,否则默认情况下它是禁用的.如果启用断言,assert false 将无条件地抛出一个 AssertionError 源自 Error.但是因为断言可以被禁用,所以有两个问题,

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,

  • 错误可能未被检测到并且
  • 控制流分析需要在 assert 之后添加一个虚拟的 return 语句(主要是混乱).
  • the error might go undetected and
  • control flow analysis requires a dummy return statement after the assert (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);

而不是 assert 后跟一个虚拟的 return.

instead of an assert followed by a dummy return.

正如评论中提到的,这是假设 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.

这篇关于断言(假)与运行时异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆