在java中,不建议在finally
块的try-chatch
部分中抛出异常,因为隐藏了throwable
中抛出的任何未处理try
的传播或catch
阻止。根据默认声纳配置文件,此做法是blocker
级违规。
声纳错误:从此finally块中删除此throw语句。
请考虑以下代码段。
例如:在finally块中关闭输入流,并在关闭流时处理可能的异常。
public void upload(File file) {
ChannelSftp c = (ChannelSftp) channel;
BufferedInputStream bis = new BufferedInputStream(file.toInputStream());
try {
String uploadLocation = Files.simplifyPath(this.fileLocation + "/" + file.getName());
c.put(bis, uploadLocation);
} catch (SftpException e) {
throw new IllegalTargetException("Error occurred while uploading " + e.getMessage());
} finally {
try {
bis.close();
} catch (IOException e) {
throw new UnsupportedOperationException("Exception occurred while closing Input stream " + e.getMessage());
}
}
}
如果您能够展示处理这些情况的传统方式,那将是非常感激的。
答案 0 :(得分:3)
处理此问题的最佳方法是使用try-with-resource
。但是,如果有人想要手动关闭连接并显示try
或catch
块的异常而不隐藏,则可以使用以下代码片段。
public void upload(File file) throws IOException {
ChannelSftp c = (ChannelSftp) channel;
BufferedInputStream bis = new BufferedInputStream(file.toInputStream());
SftpException sftpException = null;
try {
String uploadLocation = Files.simplifyPath(this.fileLocation + "/" + file.getName());
c.put(bis, uploadLocation);
} catch (SftpException e) {
sftpException = e;
throw new IllegalTargetException("Error occurred while uploading " + e.getMessage());
} finally {
if (sftpException != null) {
try {
bis.close();
} catch (Throwable t) {
sftpException.addSuppressed(t);
}
} else {
bis.close();
}
}
}