Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, how can I fail if my program is run without -ea?

Is there a way to check if the program was started with -ea so that I can exit/fail if it wasn't? If an assertion fails, I want to be informed about it. Therefore, I consider it a critical error to start up without this.

like image 621
Daniel Kaplan Avatar asked Dec 20 '22 10:12

Daniel Kaplan


1 Answers

Make an assertion guaranteed to fail.

If code after that assertion runs, assertions weren't enabled.

boolean asserted = false;

try {
   assert false;
} catch (AssertionError e) {
   asserted = true;
}

if (!asserted) {
    System.err.println("Missing '-ea' flag; exiting.");
    System.exit(1);
    // ... or throw a RuntimeException, depending on your environment.
}

That said, I'm not 100% convinced forcing assertions is a great idea. IMO assertions are more for development rather than normal error checking/handling.

like image 174
Dave Newton Avatar answered Feb 06 '23 22:02

Dave Newton