在 try 块中分配最终变量

发布于 2024-09-05 13:12:11 字数 240 浏览 7 评论 0原文

非常简短的问题:有没有更优雅的方法来做到这一点:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

寒冷纷飞旳雪 2024-09-12 13:12:11

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

final Object myObject = getObjectOrNull();

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

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

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.

合久必婚 2024-09-12 13:12:11

取决于你所说的“这个”(和“更优雅”)的意思,

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

出了什么问题

Object myObject = null;
try {
  myObject = somethingThatCanFail();
} catch (Fail f) {
  // do nothing because we can deal with myObject being null just fine
}

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
}
两仪 2024-09-12 13:12:11

这些天我倾向于这样做

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

These days I tend to do it like this

final Thingy zeFing; {
    Thingy t = null;
    try {
        t = somethingThatCanFail();
    } catch (CurveBall f) {
        // log...
    }
    zeFing = t;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文