I have an interface :
public interface FileRepository {
String insert(File file) throws IOException;
// other methods ...
}
My implementation of insert(File file)
uses local (to avoid concurrency problem) java.security.MessageDigester
which throws checked exception java.security.NoSuchAlgorithmException
from its factory method.
public FileRepositoryImpl(String digestAlgo) throws NoSuchAlgorithmException {
this.digestAlgo = digestAlgo;
MessageDigest.getInstance(digestAlgo);
}
@Override
public String insert(File file) throws IOException {
// initialize message digest
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance(digestAlgo);
} catch (NoSuchAlgorithmException e) {
LOGGER.fatal(MD_INIT_ERROR, e);
return null;
}
// other code ....
}
// other methods (may contain local MessageDigest)
My practice: As NoSuchAlgorithmException
always be a fatal error (which makes the module totally unavailable), I try to initialize a MessageDigest
in my constructor to test the parameter digestAlgo
, so the exception can be thrown by the constructor, other (earlier) than from insert(File)
. Another reason is the interface don't allow throwing NoSuchAlgorithmException
by definition.
My question: in my implementation, the code
} catch (NoSuchAlgorithmException e) {
LOGGER.fatal(MD_INIT_ERROR, e);
return null;
}
will never be reached, so I think there should be better solutions, which allows to avoid the (logically and practically) unreachable code.
Any solution/suggestion will be welcome, thanks.
Edit:
It is not really an issue when running the code. But in test, as the code is unreachable, together with some "try-catch with resources", quality analyzation tool (sonar,pmd) will consider the code "Insufficient branch coverage by unit tests", and this is a major issue in the analyze report, that's why I want to avoid this piece of code.
Another question, is it a good practice to test MessageDigest.getInstance(digestAlgo);
in my constructor? Or it's better to let insert(File)
take full responsibility of the NoSuchAlgorithmException
?