H2ONaCl
H2ONaCl

Reputation: 11309

how do I detect if assertions are turned on in the JVM?

I want the first line of my Java program output to print whether assertions are turned on. How do I do this?

Edit: An additional requirement is that the program should not terminate before doing useful work.

Upvotes: 0

Views: 199

Answers (3)

Gili
Gili

Reputation: 90180

A better performing solution (that does not throw exceptions) is:

boolean assertionsEnabled = false;
assert (assertionsEnabled = true);

Upvotes: 1

Delan Azabani
Delan Azabani

Reputation: 81492

How about this? I don't know Java, but I think this may work:

try {
    assert false;
    System.out.println("assertions are disabled");
} catch (AssertionError e) {
    System.out.println("assertions are enabled");
}

Upvotes: 2

JimN
JimN

Reputation: 3150

try {
  assert false;
  System.out.println("Assertions disabled.");
}
catch(AssertionError ae) {
  System.out.println("Assertions enabled.");
}  

Upvotes: 2

Related Questions