Make Java exit if statement fails

I am developing a multi-threaded Java program that uses different statements in the entire code and run my program using the flag ea.

Can I make my program stop immediately and exit if any statement fails?

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

include statement.
but it needs to be taken care of.

+4
source

Assert , , AssertionError . , , . , , runnables

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

, .

, "CrashOnAssertionError" runnable 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);
    }
  }
}

- :

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

, java.lang.AssertionError . , , , , .

, catch (AssertionError) , , catch. , System.exit(1).

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

+1
source

Source: https://habr.com/ru/post/1758750/


All Articles