views:

88

answers:

2

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
A: 

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
}
dty
I think the question is explicitly about assigning a `final` variable.
Joachim Sauer
Yeah, the pre-edited version forgot to mention that really important requirement!
dty
+7  A: 

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.

Joachim Sauer
+1but anyway final is just a security but you can deal without it no?
Sebastien Lorber
`final` is a very useful tool to document and enforce invariants. Additionally it is sometimes required when interacting with anonymous inner classes.
Joachim Sauer
It also supposedly helps the compiler with optimization, but I guess it can do enough of that on its own.
Bart van Heukelom
AFAIK the finally flag on local variables is only checked by the compiler, it does not exist in the bytecode and so cannot be used by hotspot. Of course hotspot might still notice that variables are not modified and generate better code.
Jörn Horstmann