Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign final variable in a try block

Very short question: Is there a more elegant way to do this:

Object tmp;
try {
 tmp = somethingThatCanFail();
} catch (Fail f) {
 tmp = null;
}
final Object myObject = tmp;
// now I have a final myObject, which can be used in anonymous classes
like image 989
Bart van Heukelom Avatar asked Jun 15 '10 12:06

Bart van Heukelom


1 Answers

You could extract the creation of the value in its own method:

final Object myObject = getObjectOrNull();

public Object getObjectOrNull() {
  try{
    return somethingThatCanFail();
  } catch (Fail f) {
    return null;
  }
}

It's longer, but depending on your definition of "elegant" it might be more elegant.

like image 143
Joachim Sauer Avatar answered Oct 11 '22 07:10

Joachim Sauer