7

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?

1
  • 3
    By the way: you don't have to use brackets when doing assertions. So: you can just write assert x > y instead of assert (x > y). Commented Apr 3, 2013 at 13:20

4 Answers 4

10

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.