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.
IllegalTargetException
and anotherUnsupportedOperationException
is thrown. Which of those would the caller get? The same is true with return-statements in finally-blocks, you'd tamper with the control flow which will lead to disaster. – Houdinifinally{}
hides any exceptions that the main body has thrown. Use try-with-resources for this sort of thing. – Evensongtry-with-ressources
is often relevant but in case when you want to trace the exception that prevents the stream from being closed or you have to perform a recovery processing, it hides the problem. – Kiln