assert(false) vs RuntimeException?

巧了我就是萌 提交于 2019-12-01 04:20:53

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.

Following the Oracle guidelines (Programming with assertions), assertions was designed for testing purposes:

An assertion is a statement in the Java programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.

Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors.

In your example, the developer assumed that the code never reaches the assert statement. If, by rare occurrence it does, the assert(false) will throw an Error (since it should never get there). This was done for testing purposes. So, use assert purely for testing purposes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!