To do internal logic checks, there are two ways in Java,
What are the differences among above two methods( performance wise, programming flexibility, etc.? Which one is considered as a good programming practice?
The key differences between exceptions and assertions are: Assertions are intended to be used solely as a means of detecting programming errors, aka bugs. By contrast, an exception can indicate other kinds of error or "exceptional" condition; e.g. invalid user input, missing files, heap full and so on.
Assertion is a programming concept used while writing a code where the user declares a condition to be true using assert statement prior to running the module. If the condition is True, the control simply moves to the next line of code.
You can use an assert to check if your logical assumption is correct. You can also use assert statements to check if the control flow is correct or not. For example, if you have a function that returns a value, you may want to put an assert statement. However, you may get a 'non-reachable' code error.
According to Sun Specification, assertion should not be used to check arguments in the public methods because it should result in appropriate runtime exception e.g. IllegalArgumentException, NullPointerException etc. Do not use assertion, if you don't want any error in any situation.
The main difference is that assert
is not guaranteed to be processed, unless assertions are explicitly enabled (either via the -ea option to java
, or programmatically). On the other hand, throwing a new AssertionError()
will always work.
Some reading information: Programming with Assertions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With