Search code examples
javaassertiondead-code

A better way to mark a line, that will never be reached?


Assuming this code snippet:

  public synchronized void kill() {
    log.info("Killing {}...", this);
    Runtime.getRuntime().halt(HALT_STATUS_CODE);
    assert false; // Line should never reach this point!
  }

Since the assert depends whether or not assertions argument is enable. Is there a better way to mark and check a line, that will never be reached at the execution time? (not only for this snippet)

Assertion doc: https://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html


Solution

  • Replace it with an IllegalStateException, replace

    assert false; 
    

    with

    throw new IllegalStateException("JVM is still running after calling halt");