gpt4 book ai didi

java - 方法中的多个 Try/Catch block 是否应该组合

转载 作者:搜寻专家 更新时间:2023-10-31 08:21:20 26 4
gpt4 key购买 nike

查看我的方法时,我不确定是否必须使用三个单独的 try/catch block 。我应该只对整个方法使用一个吗?什么是好的做法?

public void save(Object object, File file) {    

BufferedWriter writter = null;

try {
writter = new BufferedWriter(new FileWriter(file));
} catch (IOException e) {
e.printStackTrace();
}

Dictionary dictionary = (Dictionary)object;
ArrayList<Card> cardList = dictionary.getCardList();
for (Card card: cardList) {
String line = card.getForeignWord() + " / " + card.getNativeWord();
try {
writter.write(line);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
writter.flush();
writter.close();
} catch (IOException e) {
e.printStackTrace();
}
}

最佳答案

您当然不希望三个单独的代码块保持原样。在第一个 block 中,您在设置 writer 时遇到错误,但在随后的 block 中您使用 writer,但它不会如果第一个 block 失败了,这就没有意义了。当发生 I/O 错误时,您最终会抛出一个 NullPointerException——这并不理想。 :-)

在这些东西中有很大的风格空间,但这里是对您的函数的一个相当标准的重新解释。它只使用两个 block (尽管您可以选择添加第三个 block ;请参阅代码中的注释):

public void save(Object object, File file) {    

BufferedWriter writter = null;

try {
writter = new BufferedWriter(new FileWriter(file));

Dictionary dictionary = (Dictionary)object;
ArrayList<Card> cardList = dictionary.getCardList();
for (Card card: cardList) {
String line = card.getForeignWord() + " / " + card.getNativeWord();
writter.write(line); // <== I removed the block around this, on
// the assumption that if writing one card fails,
// you want the whole operation to fail. If you
// just want to ignore it, you would put back
// the block.
}

writter.flush(); // <== This is unnecessary, `close` will flush
writter.close();
writter = null; // <== null `writter` when done with it, as a flag
} catch (IOException e) {
e.printStackTrace(); // <== Usually want to do something more useful with this
} finally {
// Handle the case where something failed that you *didn't* catch
if (writter != null) {
try {
writter.close();
writter = null;
} catch (Exception e2) {
}
}
}
}

关于 finally block 的注意事项:在这里,您可能正在处理正常情况(在这种情况下 writter 将为 null),或者您可能正在处理一个您没有捕获到的异常(这并不罕见,异常的要点之一是处理在此级别上适当的内容并将其他任何内容传递给调用者)。如果 writter!null,关闭它。当您关闭它时,吃掉发生的任何异常,否则您将掩盖原始异常。 (对于这种情况,我有一些实用函数可以在吃异常的同时关闭东西。对我来说,这可能是 writter = Utils.silentClose(writter); [silentClose始终返回 null])。现在,在此代码中,您可能不会期待其他异常,但是 A) 您可以稍后更改它,并且 B) RuntimeException 可以随时发生。最好习惯使用该模式。

关于java - 方法中的多个 Try/Catch block 是否应该组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4177404/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com