What is the best way to handle errors that shouldn't ever happen?My current way to do this is to throw an exception if the 'thing that shouldn't happen' does happen, like so:/* * Restoring from a saved state. This shouldn't be  * null unless someone in the future doesn't set it properly, in which  * case they will realize they did something wrong because it may crash. */Object foo = bundle.getSerializable(foo);if (foo != null) {    doSomethingWith(foo);} else {    // This should never happen.    if (BuildConfig.DEBUG) {        throw new RuntimeException(            Foo is null!);    }    foo = new Object();    doSomethingWith(foo);}This is somewhat pointless, because this should never happen. But just in case the code gets screwed up and is released into production with foo being null, should I leave these types of checks in the code?
How should I handle exception that *should* never be thrown?
java;exceptions;comments;clean code;error handling
It's amazing how often things that should never happen do.You should throw a RuntimeException with a descriptive error message and let the application crash. If that ever happens, then you know that something is deeply wrong.