8

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
Bart van Heukelom
  • 43,244
  • 59
  • 186
  • 301
  • check out this similar SO thread: http://stackoverflow.com/questions/2773779/problems-initializing-a-final-variable-in-java – froadie Jun 15 '10 at 13:54

3 Answers3

12

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
  • 302,674
  • 57
  • 556
  • 614
  • +1 but anyway final is just a security but you can deal without it no? – Sebastien Lorber Jun 15 '10 at 13:16
  • `final` is a very useful tool to document and enforce invariants. Additionally it is sometimes required when interacting with anonymous inner classes. – Joachim Sauer Jun 15 '10 at 13:23
  • It also supposedly helps the compiler with optimization, but I guess it can do enough of that on its own. – Bart van Heukelom Jun 15 '10 at 14:42
  • 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 Jun 15 '10 at 15:22
0

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
  • 18,795
  • 6
  • 56
  • 82
0

These days I tend to do it like this

final Thingy zeFing; {
    Thingy t = null;
    try {
        t = somethingThatCanFail();
    } catch (CurveBall f) {
        // log...
    }
    zeFing = t;
}
Bart van Heukelom
  • 43,244
  • 59
  • 186
  • 301