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

时间:2016-12-20 14:53:44

标签: java sonarqube try-catch try-catch-finally try-finally

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

如果您能够展示处理这些情况的传统方式,那将是非常感激的。

1 个答案:

答案 0 :(得分:3)

处理此问题的最佳方法是使用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();
        }
    }
}