Difference between using assert and throwing AssetionError exception in java

There are two ways to perform internal logical checks in Java:

  • use the assert keyword: for example, assert (x> y) ;
  • manually display an assertion error: for example, if (y> x) add a new AssertionError ();

What are the differences between the two methods above (performance, programming flexibility, etc.? Which one is considered good programming practice?

+5
source share
4 answers

, assert , , ( -ea java, ). , new AssertionError() .

:

+9

# 1 "assert (x > y);" JVM, . , , , .

# 2 ", (y > x) AssertionError();" , assert-param. .

, "" ( , ), (.. ) / (, param not null). , .

+1

assert (x > y) , AssertionError ( ). Java , . , AssertionError, , .

0

Unfulfilled answers answer my second question (which one is considered good programming practice?). Therefore, I talked about this with one of my friends and, according to him, if some thing is private to the package, and you are the only one who calls this function (for example, private functions), then use assert. If something is publicly available, and you expect some other third-party developer to directly call this function, then do an explicit if check and throw an exception.

0
source

All Articles