gpt4 book ai didi

java - 捕获 DocumentException 是一个好主意吗?

转载 作者:行者123 更新时间:2023-12-01 17:07:46 24 4
gpt4 key购买 nike

我有一个实用方法,可以读取 xml 文件并转换为字符串,如下所示:

public static String readFile(String xmlFileName) throws IOException, DocumentException{
String xmlMsg = null;
Resource resource = null;
InputStream inputStream = null;
try{
resource = new ClassPathResource(xmlFileName);
inputStream = resource.getInputStream();
SAXReader reader = new SAXReader();
Document doc = reader.read( inputStream );
xmlMsg = doc.asXML();
}finally{
if(inputStream != null){
inputStream.close();
}
}
return xmlMsg;
}

如果我在上面的代码中捕获 DocumentException 并重新抛出它,如下所示,这是一个坏主意吗:

public static String readFile(String xmlFileName) throws IOException, DocumentException{
String xmlMsg = null;
Resource resource = null;
InputStream inputStream = null;
try{
resource = new ClassPathResource(xmlFileName);
inputStream = resource.getInputStream();
SAXReader reader = new SAXReader();
Document doc = reader.read( inputStream );
xmlMsg = doc.asXML();
}catch (DocumentException e){
throw new DocumentException("some message");
}finally{
if(inputStream != null){
inputStream.close();
}
}
return xmlMsg;
}

那么,将处理 DocumentException 的责任留给调用者是不是一个坏主意?

最佳答案

不,让调用者处理异常就可以了 - throw early catch late .

我遇到的问题是:

}catch (DocumentException e){
throw new DocumentException("some message");

为什么要捕获 (DocumentException e),然后抛出一个删除所有有用信息的新实例?您可以一开始就不捕获它,然后让它渗透到能够处理它的人那里。

此外,请使用 Java 7 try-with-resources 而不是 finally。所以,你的代码应该是:

public static String readFile(String xmlFileName) throws IOException, DocumentException {
try (final InputStream is = new ClassPathResource(xmlFileName).getInputStream()) {
final SAXReader reader = new SAXReader();
final Document doc = reader.read(inputStream);
return doc.asXML();
}
}

我已经删除了声明为 null 的变量,然后重新赋值,我讨厌这种做法,许多其他 Java 开发人员也是如此 - 摆脱这种习惯。 在需要时声明它们立即分配它们。在垃圾收集语言中,最小作用域原则非常重要。

由于某种原因,我还将其更改为直接返回,而不是存储该值。

关于java - 捕获 DocumentException 是一个好主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24691511/

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