David B
David B

Reputation: 29998

Make java program exit if assertion fails

I'm developing a multi-threaded Java program use different assertions throughout the code and run my program using the ea flag.

Can I make my program immediately stop and exit when any assertion fails?

Upvotes: 4

Views: 6171

Answers (3)

Justin Ardini
Justin Ardini

Reputation: 9866

When assertions are enabled, they throw a java.lang.AssertionError upon failing. As long as you don't try to catch this, the thread throwing the exception will stop when an assertion fails.

If you want any other behavior, you can catch (AssertionError) and do whatever you want inside the catch statement. For example, call System.exit(1).

If you want AssertionError to include an error message, you need to use the assert Expression1 : Expression2; form of assert. For more information, read this.

Upvotes: 2

Matt Wonlaw
Matt Wonlaw

Reputation: 12443

Assert will stop whatever thread threw the assertion, assuming the AssertionError isn't caught. Although I would think that killing that thread would be enough and you wouldn't want to go and kill the whole program. Anyhow, to actually kill the entire program, just wrap your runnables with a

try { 
} catch (AssertionError e) { 
   System.exit(1);
} 

which will kill the program when the assertion is raised.

So you could make a "CrashOnAssertionError" runnable to wrap all of your runnables:

public class CrashOnAssertionError implements Runnable {
  private final Runnable mActualRunnable;
  public CrashOnAssertionError(Runnable pActualRunnable) {
    mActualRunnable = pActualRunnable;
  }
  public void run() {
    try {
      mActualRunnable.run();
    }  catch (AssertionError) {
       System.exit(1);
    }
  }
}

And then you can do something like:

Runnable r = new CrashOnAssertionError(
  new Runnable() { 
    public void run() {
     // do stuff 
    }
 });
new Thread(r).start();

Upvotes: 4

Jigar Joshi
Jigar Joshi

Reputation: 240908

try {
    code that may generate AssertionError
} catch (AssertionError e) {
       System.exit(0);//logging or any action
}  

enable assertion also.
but it must be taken care.

Upvotes: 5

Related Questions