I'm reformatting some legacy code that I don't fully understand, and in it there are several variable assignments that conditionally assign variables to the output of one of two formatting functions, using exception catching like so:
String myString;
try {
myString= foo(x);
} catch (Exception e) {
myString= bar(x);
}
This seems like an abuse of exception handling, and anyway it's a lot of repeated boilerplate code for a lot of variable assignments. Without digging into foo
to identify the conditions that might cause exceptions, can I simplify this using a ternary operator expression? I.e. something like this:
String myString = foo(x) ? foo(x) : bar(x)
but catching the exception that might be thrown by foo(x)
. Is there a way to do this in this one-liner? Or if not, is there a better one-line expression that chooses between two assignments based on a possible exception? I am using Java 8.