I just discovered some lovely code in our companies app that uses Try-Catch blocks as logical operators.
Meaning, "do some code, if that throws this error, do this code, but if that throws this error do this 3rd thing instead".
It uses "Finally" as the "else" statement it appears.
I know that this is wrong inherently...
How do you know that? I gave up all that sort of "knowledge" and now just believe that the simplest code is the best. Suppose you want to convert a string to an Optional which is empty if the parse fails. There is nothing wrong with:
try {
return Optional.of(Long.valueOf(s));
} catch (NumberFormatException) {
return Optional.empty();
}
I completely disagree with the usual interpretation of "Exceptions are for exceptional conditions". When a function cannot return a usable value or a method cannot meet its post-conditions, throw an exception. It doesn't matter how often these exceptions are thrown until there is a demonstrated performance problem.
Exceptions simplify code, by allowing the separation of error handling from the normal flow. Just write the simplest possible code, and if it is easier to use try-catch or to throw an exception, then do that.
Exceptions simplify testing by reducing the number of paths through the code. A function with no branches will either complete or throw an exception. A function with multiple if
statements to check for error codes has many possible paths. It is very easy to get one of the conditions wrong, or to forget one completely, so that some error condition is ignored.
try
'd. Not every exceptional case which warrants an exception in general has to be fatal in this specific case. So, could you do it in a simpler, equally or more robust way without using exceptions?