Re: Understanding Exceptions
On 11/7/2010 9:47 AM, Steve Crook wrote:
On Sun, 07 Nov 2010 10:30:52 -0500, Eric Sosman wrote in
1) Declare your method with "throws NoSuchAlgorithmException" and
require the caller to cope. This may seem onerous, but consider: the
caller usually knows more about the overall state of the application
than the lower-level callee, and as such may be in a better position
to decide what to do.
I like this solution. Whilst my particular application is entirely
dependent on SHA-256 I should code the method in such a manner as to
make the surrounding object reusable. For this to be effective the
higher level code must handle the exception.
I haven't seen this posted yet, maybe I missed it:
I don't like this solution above. Why? Why inform the calling code
that you might not find the algorithm you were looking for? They did
not pass the name of the algorithm in as a parameter. There's nothing
the caller could do about it. There's a maxim, I believe, about only
throwing exceptions when the caller could take some action to rectify
the situation.
So I'd write you code thusly:
private static String sha256(byte[] password, byte[] iv) {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(iv);
byte[] hash = md.digest(password);
return byteArrayToHexString(hash);
}
Which is the same as your original post. NoSuchAlgorithmException is
already unchecked; there's no need to wrap it. (If the algorthim name
were being passed in by the caller, then it might be better to wrap so
the caller could more easily catch a checked exception.)
The only thing I might add is a log statement. Since the exception is
unchecked, no one else is likely to log it. Plus you can add some extra
information to the log, since you have a better idea than higher level
code what is going on.
private static String sha256(byte[] password, byte[] iv) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
} catch( NoSuchAlgorithmException ex ) {
Logger.getLogger().severe( "could not find algorithm SHA-256: "
+ ex + "\n. Please make sure you have jcrypt.jar in your" +
" classpath." );
throw ex;
}
md.update(iv);
byte[] hash = md.digest(password);
return byteArrayToHexString(hash);
}
Which will be a bit more informative to the person diagnosing this
error. Note I just re-throw the same exception; I don't make a new one.
Also please note this code was not tested, and I have no idea if
jcrypt.jar is really the correct file. It's just an example.