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?
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?
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.
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.
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();