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

java中,不建议在try-chatch块的finally部分中抛出异常,因为隐藏了try或catch块中抛出的任何未处理的throwable的传播.根据默认声纳配置文件,此做法是阻止级别违规.

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.但是,如果有人想要手动关闭连接并显示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();
        }
    }
}

转载注明原文:如何在java中的finally块中处理抛出异常 - 代码日志