如何在 java 的 finally 块中处理抛出异常

How to handle throw exceptions inside finally block in java

在 java 中,不建议在 try-chatch 块的 finally 部分内抛出异常,因为隐藏了抛出的任何未处理的 throwable 的传播trycatch 块。根据默认声纳配置文件,这种做法违反了 blocker 级别。

Sonar Error: Remove this throw statement from this finally block.

请考虑以下代码片段。

例如:在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());
            }
        }
    }

如果您能展示处理这些情况的常规方法,我们将不胜感激。

处理此问题的最佳方法是使用 try-with-resource。但是如果有人想手动关闭连接并显示 trycatch 块的异常而不隐藏,下面的代码片段是解决方案。

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();
        }
    }
}