tags:

views:

91

answers:

3

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?

+1  A: 

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.

Justin Ardini
The thread that throws the assertion will stop, not the entire program.
mlaw
By the way, if your code is sprinkled with `catch (Exception e)` or even worse `catch (Throwable t)`, then you are a horrible, horrible person.
Paul Tomblin
@mlaw: Of course, missed the multithreaded part of the question. Edited.
Justin Ardini
+4  A: 
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.

org.life.java
+1  A: 

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();
mlaw
+1: I like the `Runnable` approach, though `CrashOnAssertionError` is not the clearest class name, it sounds like an error itself.
Justin Ardini
@Justin True. CrashOnAssertErrorRunnable ? :/
mlaw
Now that's a true Java name. :)
Justin Ardini