我有一个实用程序方法,它读取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;
}
Run Code Online (Sandbox Code Playgroud)
如果我在上面的代码中捕获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;
}
Run Code Online (Sandbox Code Playgroud)
那么,将处理DocumentException的责任留给调用者是不是一个坏主意?
不,让打电话者处理Exception罚款 - 提前赶上.
我遇到的问题是:
}catch (DocumentException e){
throw new DocumentException("some message");
Run Code Online (Sandbox Code Playgroud)
你为什么要catch (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();
}
}
Run Code Online (Sandbox Code Playgroud)
我删除了声明null然后重新分配的变量,我讨厌这种做法,许多其他Java开发人员也是如此 - 摆脱这种习惯.在需要时声明事物并立即分配.在垃圾收集语言中,最小范围的原则非常重要.
我也将其更改为return直接而不是出于某种原因存储值.