How to handle throw exceptions inside finally block in java

11.5k views Asked by At

In java, it is not recommended to throw exceptions inside finally section in try-chatch block due to hide the propagation of any unhandled throwable which was thrown in the try or catch block. This practice is a blocker level violation according to default sonar profile.

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

Please consider the following code snippet.

e.g.: close input stream inside the finally block, and handle possible exceptions might be occurred when closing the stream.

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

It would be grateful if you can show the conventional way of handling these situations.

1

There are 1 answers

0
Hiran Perera On BEST ANSWER

Best way to handle this problem is to use try-with-resource. But if someone want to close the connection manually and show the exception of the try or catch block without hiding, following code snippet is the solution.

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