Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using assert and throwing AssetionError exception in java

To do internal logic checks, there are two ways in Java,

  1. use the assert keyword: e.g, assert(x>y);
  2. manually throw assertion error: e.g, if(y>x) throw new AssertionError();

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

like image 856
RoboAlex Avatar asked Apr 03 '13 13:04

RoboAlex


People also ask

What is the difference between assertion and exception?

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.

What do you mean by assertion and AssertionError?

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.

When should you use assert?

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.

What is the advantage of assertion and where we should not use it?

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.


1 Answers

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

like image 161
Perception Avatar answered Sep 22 '22 03:09

Perception