assert(false) vs RuntimeException?

后端 未结 2 1203
陌清茗
陌清茗 2021-01-12 05:54

I\'m reading the source of XWalkUIClientInternal and I ran into the following code:

    switch(type) {
        case JAVASCRIPT_ALERT:
            return onJs         


        
2条回答
  •  耶瑟儿~
    2021-01-12 06:42

    The biggest difference between

    assert false;
    

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

    throw new RuntimeException();
    

    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 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);
    

    instead of an assert followed by a dummy return.

    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.

提交回复
热议问题