When to use an assertion and when to use an exception

前端 未结 11 2122
暖寄归人
暖寄归人 2020-11-27 09:28

Most of the time I will use an exception to check for a condition in my code, I wonder when it is an appropriate time to use an assertion?

For instance,



        
11条回答
  •  醉酒成梦
    2020-11-27 09:49

    I confess I'm a little confused by your question. When an assertion condition is not met, an exception is thrown. Confusingly this is called AssertionError. Note that it's unchecked, like (for example) IllegalArgumentException which is thrown in very similar circumstances.

    So using assertions in Java

    1. is a more concise means of writing a condition/throw block
    2. permits you to turn these checks on/off via JVM parameters. Normally I would leave these checks on all the time, unless they impact runtime performance or have a similar penalty.

提交回复
热议问题