Possible Duplicate:
What does assert do?
assert tests the programmer's assumption during development without writing exception handlers for an exception This is what i got, when i was searching about the assert.
Apart from this, people also said, it is alternative of exception handling. Assertion will come into the picture when you don't want to take the time to write the exception handling code. But, i didn't get the working and uses. Anyone explain this example.
class AssertExample {
public static void main(String[] args) {
int x = 0;
assert (x > 0) ? "assertion failed" : "assertion passed";
System.out.println("finished");
} }
assert
isn't a way to handle exceptions, it's a way to detect them. (Thus, the descriptions you're finding seem a little off the mark to me.) It's basically a way to say:
This should be true. If it isn't, throw an error.
How you handle that error is an entirely different concern. You might handle it right there in the function that detected it, you might handle it in the function that called it, you might handle it at the very top of the stack at the application level, etc.
Keep in mind that there's a significant difference between catching an exception (which is a construct of the programming language being used) and meaningfully handling an exception (which is a logical construct independent of the language being used). Only catch exceptions where you can actually do something about them. Otherwise, let them bubble up the stack to other code that can do something about them. (But since assert
doesn't catch errors, it throws them, it should be used exactly where you're trying to use it... the point at which an error can be detected, even if it can't be handled.)
Looking at your attempt to use assert
, it looks like you're close. This isn't really the correct usage:
assert (x > 0) ? "assertion failed" : "assertion passed";
You're treating the assert
as though it's just a boolean. And then, using the ? :
operator, you're keying off of that boolean to... well... not really do anything. Just return a string ("assertion failed"
or "assertion passed"
) to a line of code that doesn't do anything with that string.
Close, but not quite.
The assert
itself is doing more than just checking a condition. It's responding to the condition by either throwing an error or allowing the code path to continue. It uses an :
operator, but not as part of the ? :
operator. So I think what you're trying to do is this:
assert (x > 0) : "assertion failed";
This is basically saying:
x should always be greater than 0. If it isn't, something is very wrong. Stop doing anything and raise an error.
This will raise an AssertionError
with the message "assertion failed"
(which, naturally, you'd want to replace with a more meaningful and useful message, including any helpful runtime information about the values being examined to help with your debugging).
Then, elsewhere, you would handle that AssertionError
and respond to it in some way.
Using the assert
is very similar to something like this, only shorter and a little more expressive to its intent:
if (x <= 0) throw new CustomException("assertion failed");
As you can see, the assert
is just a little cleaner in that it:
- Uses a specific keyword to call attention to the fact that it's checking a condition for the sole purpose of validating an assumption. An
if
might be doing that, or it might be forking off a new code path for any other reason.
- Throws a specific error which can be filtered apart from other errors. Note my use of a
CustomException
to do the same thing, but AssertionError
is more commonly known/expected.
- Uses less code.
- Demonstrates the true condition, as opposed to the inverse or false condition. In the majority of cases, the true condition is easier to read and more clearly expresses what the code intends.
- Follows convention and is more idiomatic.
- Sets the code apart from the rest of the code as being for a specific purpose, indicating to other developers that the assertion should be only an assertion. (So other developers shouldn't modify it as a second code path, possibly adding side-effects to the assertion.)
- Can be very easily turned on or off globally for the running application. Java allows you to enable or disable the checking of assertions during any given runtime context. This is very handy for globally managing assertions as a cross-cutting concern.
Wikipedia:
In computer programming, an assertion is a predicate (a true–false statement) placed in a program to indicate that the developer thinks that the predicate is always true at that place. The use of assertions helps the programmer design, develop, and reason about a program.
You can enable assertions at runtime using -ea
switch. Assertion can also be enabled selectively
java -ea:pl.maciejziarko.service.UserService
Some rules about assertions (from SCJP Sun Certified Programmer for Java 6 Study Guide):
- Don't Use Assertions to Validate Arguments to a Public Method
- Do Use Assertions to Validate Arguments to a Private Method
- Don't Use Assertions to Validate Command-Line Arguments
- Do Use Assertions to Check for Cases that You Know Are Never, Ever
Supposed to Happen
- Don't Use Assert Expressions that Can Cause Side Effects
Assert is for validating assumptions about your code during development time.
They tend to be used as a kind of poor man's design by contract.
For example, I use them for validating pre/post conditions and invariants of the code.