Hir*_*era 5 java try-catch try-catch-finally try-finally sonarqube
在Java中,不建议finally在try-chatch块的section中抛出异常,因为它会隐藏任何throwable在tryor 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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您能展示处理这些情况的常规方法,将不胜感激。
处理此问题的最佳方法是使用try-with-resource. 但是如果有人想手动关闭连接并显示tryorcatch块的异常而不隐藏,下面的代码片段是解决方案。
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)