开发者

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 hav开发者_如何学Ce a final myObject, which can be used in anonymous classes


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.


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
}


These days I tend to do it like this

final Thingy zeFing; {
    Thingy t = null;
    try {
        t = somethingThatCanFail();
    } catch (CurveBall f) {
        // log...
    }
    zeFing = t;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜