Reputation: 4563
What exactly happens when a Java assertion fails? How does the programmer come to know that an assertion has failed?
Thanks.
Upvotes: 12
Views: 14527
Reputation: 1
Programmer can write try catch block so if a error has occurred then it can be caught in catch and the programmer can come to know
try
{
assert false;
}
catch(Exception e)
{
System.out.println("Error has occured");
}
Upvotes: 0
Reputation: 3492
It throws an Error
. It is just like when you get a NullPointerException
, but it's a subclass of java.lang.Error
. The name is AssertionError
.
It's like a NullPointerException
in the sense that you don't have to declare the throws or anything, it just throws it.
assert(false);
is like
throw new AssertionError();
if you run your program with the -ea
flag passed to the java program (VM).
Upvotes: 0
Reputation: 13946
It throws an AssertionError
which is a subclass of Error
. As an Error
generally and as a failed assertion in particular, you likely should not try to catch it since it is telling you there's a significant abnormality in your code and that if you continue you'll probably be in some undefined, unsafe state.
Upvotes: 2
Reputation: 10184
It throws an AssertionError. Howeveer, you have to compile the program with the -ea or -enableassertions flag to have it generate an actual exception
Upvotes: 1
Reputation: 10493
An assertion will only fail if you enabled assertions in the JVM when it started. You can do that by specifying the parameter -ea in the command line. If you do that, then this block of code will throw an AssertionError
when it is executed:
public void whatever() {
assert false;
}
Assertions should be used to detect programming errors only. If you are validating user input or something on those lines, don't use assertions.
Upvotes: 4
Reputation: 20969
If an assertion fails and assertion are enabled at runtime it will throw an AssertionError.
Usually you use assert statements in JUnit testings, when building your application you are running a test utility that will check for errors and tell you.
Take a look at this: Programming With Assertions
Upvotes: 1
Reputation: 43159
If assertions are enabled in the JVM (via the -ea
flag), an AssertionError
will be thrown when the assertion fails.
This should not be caught, because if an assertion fails, it basically means one of your assumptions about how the program works is wrong. So you typically find out about an assertion failure when you get an exception stack trace logged with your thread (and possibly whole program) terminating.
Upvotes: 9