Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

In Java, which is more highly recommended, and why? Both types will throw exceptions, so in that regard handling them is the same. assert is slightly shorter, but I'm not sure how much that matters.

public void doStuff(Object obj) {
    assert obj != null;
    ...
}

vs

public void doStuff(Object obj) {
    if (obj == null) {
        throw new IllegalArgumentException("object was null");
    }
    ...
}
share|improve this question
add comment

4 Answers 4

up vote 31 down vote accepted

BEWARE!

Assertions are removed at runtime unless you explicitly specify to "enable assertions" when compiling your code. Java Assertions are not to be used on production code and should be restricted to private methods (see Exception vs Assertion), since private methods are expected to be known and used only by the developers. Also assert will throw AssertionError which extends Error not Exception, and which normally indicates you have a very abnormal error (like "OutOfMemoryError" which is hard to recover from, isn't it?) you are not expected to be able to treat.

Remove the "enable assertions" flag, and check with a debugger and you'll see that you will not step on the IllegalArgumentException throw call... since this code has not been compiled (again, when "ea" is removed)

It is better to use the second construction for public/protected methods, and if you want something that is done in one line of code, there is at least one way that I know of. I personally use the Spring Framework's Assert class that has a few methods for checking arguments and that throw "IllegalArgumentException" on failure. Basically, what you do is:

Assert.notNull(obj, "object was null");

... Which will in fact execute exactly the same code you wrote in your second example. There are a few other useful methods such as hasText, hasLength in there.

I don't like writing more code than necessary, so I'm happy when I reduce the number of written lines by 2 (2 lines > 1 line) :-)

share|improve this answer
    
Ah, I forgot about assertions being removed! Great answer. I'll wait a bit to see if anything else comes in, then accept it :) –  Daenyth Feb 27 '12 at 19:17
    
Thank you very much –  Jalayn Feb 27 '12 at 21:34
    
Note that there is no flag that removes assertions at compile time (although they may be removed via conditional compliation). Assertions are disabled at runtime by default (I think the JVM treats them as NOOP), but can be enabled via java -ea and programmatically. @Jalayn I think having assertions in production code is perfectly valid, as they are useful for debugging in the field –  Justin Muller Jan 24 at 7:30
add comment

You need to use an exception. Using an assertion would be a misuse of the feature.

Unchecked exceptions are designed to detect programming errors of the users of your library, while assertions are designed to detect errors in your own logic. These are separate issues that should not be mixed.

For example, an assertion

assert myConnection.isConnected();

means "I know that each code path leading to this assertion ensures that myConnection is connected; if the code above failed to get a valid connection, it should have thrown an exception or return before reaching this point."

On the other hand, a check

if (!myConnection.isConnected()) {
    throw new IllegalArgumentException("connection is not established");
}

means that "Calling my library without establishing a connection is a programming error".

share|improve this answer
1  
Great point! Thanks. –  Daenyth Feb 27 '12 at 19:18
1  
This information is really helpful, but I'm accepting Jalayn's since it points out how I could potentially introduce a bug with the assert method. –  Daenyth Feb 27 '12 at 21:43
1  
excellent point "Unchecked exceptions are designed to detect programming errors of the users of your library, while assertions are designed to detect errors in your own logic. These are separate issues that should not be mixed." –  Asim Ghaffar Sep 19 '13 at 12:41
add comment

IMO the second one is slightly better because it brings more information and could be further extended (e.g. by extending exception class) to be even more informative, also it doesn't use negative comparison which is easier to understand.

share|improve this answer
add comment

I always prefer to throw IllegalArgumentException over assertions.

Assertions are used mostly in JUnit or other testing tools, to check/assert test results. So it might give false impression to other developers that your method is a test method.

Also it makes sense to throw IllegalArgumentException when a method has been passed an illegal or inappropriate argument. This is more consistent with the Exception Handling convention followed by Java developers.

share|improve this answer
1  
Assertions were around about 40 years before JUnit - ask a C programmer about ASSERT macros. –  JBRWilkinson Feb 22 '13 at 22:04
1  
this question is not about c; its about Java. So i have replied in context of Java. –  rai.skumar Feb 23 '13 at 5:43
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.