在Java中,不建议在finally
块中丢弃CC_1块中的异常,因为隐藏了在try
或catch
块中丢弃的任何未手动throwable
的传播。根据默认声纳配置文件,这种做法是违反blocker
级别的级别。
声纳错误:从此最终删除此投掷语句。
请考虑以下代码段。
例如:关闭最后块内的输入流,并在关闭流时可能会发生可能的异常。
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());
}
}
}
如果您可以显示处理这些情况的常规方式,这将是很感激的。
处理此问题的最佳方法是使用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();
}
}
}