Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java assertion error does not throw error

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");
  }
} 
like image 847
user1050619 Avatar asked Jul 29 '13 17:07

user1050619


People also ask

How do you fix an assertion error in Java?

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.

Does assert throw an exception Java?

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.

Do assertions throw exceptions?

Assert. Throws returns the exception that's thrown which lets you assert on the exception.

What causes an assertion error in Java?

As with many other languages, the AssertionError in Java is thrown when an assert statement fails (i.e. the result is false).


1 Answers

You need to set the -ea (Enable Assertions) in your JVM options.


Unrelated, but you almost always want string1.equals(string2) rather than ==.

like image 116
Dave Newton Avatar answered Oct 06 '22 17:10

Dave Newton