Why doesn't my assert statement yield any result? I think the first assert statement should fail, but I don't see anything being displayed on Eclipse.
I'm using Eclipse to run this program.
package java.first;
public class test {
public static void main(String[] args) throws Exception {
String s = "test1";
assert (s == "test");
s = "test";
assert (s == "test");
}
}
In order to handle the assertion error, we need to declare the assertion statement in the try block and catch the assertion error in the catch block.
Another problem with using assertions for argument checking is that erroneous arguments should result in an appropriate runtime exception (such as IllegalArgumentException , IndexOutOfBoundsException , or NullPointerException ). An assertion failure will not throw an appropriate exception.
Assert. Throws returns the exception that's thrown which lets you assert on the exception.
As with many other languages, the AssertionError in Java is thrown when an assert statement fails (i.e. the result is false).
You need to set the -ea
(Enable Assertions) in your JVM options.
Unrelated, but you almost always want string1.equals(string2)
rather than ==
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With