When to use an assertion and when to use an exception

前端 未结 11 2043
暖寄归人
暖寄归人 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:46

    According to this doc http://docs.oracle.com/javase/6/docs/technotes/guides/language/assert.html#design-faq-general, "The assert statement is appropriate for nonpublic precondition, postcondition and class invariant checking. Public precondition checking should still be performed by checks inside methods that result in particular, documented exceptions, such as IllegalArgumentException and IllegalStateException."

    If you want to know more about precondition, postcondition and class invariant, check this doc: http://docs.oracle.com/javase/6/docs/technotes/guides/language/assert.html#usage-conditions. It also contains with examples of assertions usage.

    0 讨论(0)
  • 2020-11-27 09:48

    You can use this simple difference in mind while their usage. Exceptions will be used for checking expected and unexpected errors called checked and unchecked error while assertion is used mainly for debugging purposes at the run time to see whether the assumptions are validated or not.

    0 讨论(0)
  • 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.
    0 讨论(0)
  • 2020-11-27 09:56

    Well, back at Microsoft, the recommendation was to throw Exceptions in all APIs you make available publicly and use Asserts in all sorts of assumptions you make about code that's internal. It's a bit of a loose definition but I guess it's up to each developer to draw the line.

    Regarding the use of Exceptions, as the name says, their usage should be exceptional so for the code you present above, the getGroup call should return null if no service exists. Exception should only occur if a network link goes down or something like that.

    I guess the conclusion is that it's a bit left down to the development team for each application to define the boundaries of assert vs exceptions.

    0 讨论(0)
  • 2020-11-27 09:57

    Remember assertions can be disabled at runtime using parameters, and are disabled by default, so don't count on them except for debugging purposes.

    Also you should read the Oracle article about assert to see more cases where to use - or not to use - assert.

    0 讨论(0)
提交回复
热议问题