Post Closed as "duplicate" by gnat, Bart van Ingen Schenau, Jimmy Hoffa, amon, GlenH7 of
2 edited tags
| link
1
source | link

How should I handle exception that *should* never be thrown?

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?