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
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
Depends what you mean by "this" (and "more elegant")
I'm not sure why you think you need tmp AND myObject, but there's no way to avoid having one of those declarations outside the try block IF you want to access it in the catch block.
What's wrong with
Object myObject = null;
try {
myObject = somethingThatCanFail();
} catch (Fail f) {
// do nothing because we can deal with myObject being null just fine
}
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.