assert(false) vs RuntimeException?

后端 未结 2 1199
陌清茗
陌清茗 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:48

    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.

提交回复
热议问题