Jayen
Jayen

Reputation: 6069

java assert without exception

We have some java code that we would ideally like to run in three ways:

  1. Throw an exception when an assert fails
  2. Print a stack trace, but otherwise continue when an assert fails
  3. Ignore an assert

This is to be run in three different environments (development, testing, production, respectively). We can switch between the first and last by using the -ea JVM option, but is it possible to do the second?

Thanks.

EDIT: we already have assert statements everywhere. we prefer to change this option at run-time without changing our code.

Upvotes: 1

Views: 2349

Answers (3)

obataku
obataku

Reputation: 29646

You can achieve #2 very easily, since assert throws an AssertionError.

try {
  assert false;
} catch (final AssertionError error) {
  error.printStackTrace();
}
System.out.println("survived!");

Upvotes: 0

Makoto
Makoto

Reputation: 106430

It almost seems like you want to use unit testing for this instead of Java's built-in assert. Look into what JUnit could do for you and your team.

You can set up tests to run, and they'll notify you of failure. If you want a stack trace, you can create your own by raising/catching an exception, then use e.printStackTrace().

Upvotes: 4

BlackHatSamurai
BlackHatSamurai

Reputation: 23483

You can't, not using Assert. Assert is specifically designed to fail and not be ignored.

Upvotes: 0

Related Questions