RoboAlex
RoboAlex

Reputation: 5015

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?

Upvotes: 6

Views: 1978

Answers (4)

RoboAlex
RoboAlex

Reputation: 5015

Non of above answers answer my second question (Which one is considered as a good programming practice?). So I talked regards this with one of my friend and according to him, If some thing is private to the package and you are the only one calling that function (e.g, private functions) then use assert. If something is public and you expect some other third party developer may directly call the function, then do a explicit if check and throw the exception.

Upvotes: 0

Andy
Andy

Reputation: 1994

Way #1 "assert(x>y);" uses a JVM feature which is turned off by default. However, it gives you more flexibility since you can turn it on and off as you like with one single parameter.

Way #2 "if(y>x) throw new AssertionError();" will always be executed, you can't turn it off via the assert-param. It is just an exception.

I've often seen people use Exceptions for "real" errors (network not available, wrong input provided), while assertions are often used (i.e. turned on) during development/integration for very basic checks (e.g. param not null). IMO, it's hard to draw the line.

Upvotes: 1

IndoKnight
IndoKnight

Reputation: 1864

When assert(x>y) fails, then it would raise AssertionError(provided assertions are enabled). The advantage of using java assertions is that it can be enabled or disabled during compile time. You can disable assertions for production environment which improves performance compared to raising manually AssertionError in which you always perform assertions thereby reducing performance.

Upvotes: 0

Perception
Perception

Reputation: 80603

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

Upvotes: 9

Related Questions