(How) is it possible to catch an exception in a Java ternary operator statement?

workerjoe :

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.

Bernhard Josephus :

Washcloth answer is already clear. Just wanna add a bit though about your statement:

it's a lot of repeated boilerplate code for a lot of variable assignments.

If you don't want to assign a variable repeatedly, you can create a new method to return String value as below:

String myString = assign(x);

String assign(String x) {
    try {
        return foo(x);
    } catch (Exception e) {
        return bar(x);
    }
}

You only need to assign the variable once with the above method.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113062&siteId=1