Using AssertionError and assertions in java

前端 未结 2 624
悲&欢浪女
悲&欢浪女 2020-12-31 07:42

I use assertions in Java in a standard way, having them turned on in my IDE. So they are not part of production release. Lately I have been seeing code examples with t

2条回答
  •  萌比男神i
    2020-12-31 08:38

    In the technote "Programming With Assertions: Control Flow Invariants" the following code is given:

    void foo() {
        for (...) {
          if (...)
            return;
        }
        assert false; // Execution should never reach this point!
    }
    

    But the following note is given as well:

    Note: Use this technique with discretion. If a statement is unreachable as defined in the Java Language Specification, you will get a compile time error if you try to assert that it is not reached. Again, an acceptable alternative is simply to throw an AssertionError.


    You may not expect an AssertionError to be thrown when assertions are turned off. As AssertionError constructors are public, and since there is likely no substitution for AssertionError(String message, Throwable cause), I guess that you should expect them even if they are turned off.


    Throwing an AssertionError on unreachable code (i.e. without any real expression to be evaluated) will never slow down the code, as Jon Skeet suggested, so it won't hurt with regards to performance.


    So in the end throwing the AssertionError seems OK.

提交回复
热议问题