在try块中分配final变量

时间:2010-06-15 12:39:07

标签: java try-catch final

非常简短的问题:有更优雅的方法吗:

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

2 个答案:

答案 0 :(得分:12)

您可以使用自己的方法提取值的创建:

final Object myObject = getObjectOrNull();

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

它更长,但根据你对“优雅”的定义,它可能会更优雅。

答案 1 :(得分:0)

取决于你的意思“这个”(以及“更优雅”)

我不确定为什么你认为你需要tmp和myObject,但是如果你想在catch块中访问它,就没有办法避免在try块之外使用其中一个声明。

有什么问题
Object myObject = null;
try {
  myObject = somethingThatCanFail();
} catch (Fail f) {
  // do nothing because we can deal with myObject being null just fine
}
相关问题