Why are you handling an error that never happens?
Computer programming deals with absolutes. There is no such thing as should, could and maybe. Either the error will happen or it will not. Adding error handling code for something that has a 0% chance of occurring is code smell. Good code handles that off change of 0.01% when it does happen.
A good way to think of it is like this.
If you only add error handling for 99% of the possible problems, then there only needs to be 100 problems for the source code to have an unhandled problem.
Overtime source code will grow to deal with thousands of problems...
Don't mix error handling with business logic
One problem I see all the time is source code that has been shotgun blasted with error handling. Especially in Java where exception handling is enforced by compiler error.
It makes it difficult to read what the intent of a function is when it branches many times to handle all the different error cases.
Instead, separate your error handling into specialized functions. Keep the original function focused on a single intent.
For example;
public Object getSerializableSafely(Bundle bundle, String name)
{
Object foo = bundle.getSerializable(name);
if (foo != null)
{
return foo;
}
else if (BuildConfig.DEBUG) {
throw new RuntimeException("Foo is null!");
}
return null;
}
public boolean Worker()
{
Object foo = getSerializableSafely(bundle, "foo");
if (foo == null)
{
return false;
}
// do work with foo
return true;
}
Now, there is nothing wrong with throwing a runtime exception in debug builds. They can be great time savers because they take the debugger right to where the problem is.
The problem is trying to create functions like Worker
and expect them to never fail. Reporting true/false as the result of an operation is much better than wrapping everything in try/catch.
If you were using an XML parsing API. Would you want it to throw an exception if you feed it invalid XML or would you want the parse function to return false? Keep your exception handling related to things that are the exceptional case, and use return results to communicate the result of a function.