Jacksum NoSuchAlgorithmException

2019-09-15 09:33发布

问题:

I'm trying to use the Jacksum API to generate a Whirlpool hash, but I'm getting a NoSuchAlgorithmException:

import java.security.NoSuchAlgorithmException;
import jonelo.jacksum.JacksumAPI;
import jonelo.jacksum.algorithm.AbstractChecksum;

public static String genHash(String inText) {

    AbstractChecksum checksum = null;
    checksum = JacksumAPI.getChecksumInstance("whirlpool");
    checksum.update(inText.getBytes());
    return checksum.getFormattedValue();

}

I tried other popular algorithms (sha256, md5) and they all apparently "aren't such".

./libsdpg.java:27: error: unreported exception NoSuchAlgorithmException; must be caught or declared to be thrown
    checksum = JacksumAPI.getChecksumInstance("whirlpool");
                                             ^
1 error

EDIT: I added the try-catch, and now it's actually getting the error.

回答1:

You are not actually "getting" an exception. The compiler is telling you that you have failed to appropriately handle a checked exception.

The JacksumAPI#getChecksumInstance(java.lang.String) method throws a checked exception called NoSuchAlgorithmException. A checked exception must either be explicitly handled (using try-catch), or the enclosing method must declare that it throws it by including it in its signature. So your options are:

try {
   ...
   checksum = JacksumAPI.getChecksumInstance("whirlpool");
   ...
} catch(NoSuchAlgorithmException e) {
   //handle the exception
}

or change your method signature to:

public static String genHash(String inText) throws NoSuchAlgorithmException {
    ...
}

Keep in mind with the second option you have merely pushed the handling up to a higher level (i.e., where genHash is called); you will essentially have to handle it at some point.



回答2:

You are not getting the NoSuchAlgorithmException. Instead the compiler is saying that the getChecksumInstance() throws a checked exception, NoSuchAlgorithmException which needs to be handled, since you've not already done that.

You can do that either by having a throws clause in your genHash()(you'll need to handle the exception in the method where genHash() is called though)

// Solution 1
public static String genHash(String inText) throws NoSuchAlgorithmException {

or by surrounding the call to getChecksumInstance() within a try-catch.

// Solution 2
try {
    checksum = JacksumAPI.getChecksumInstance("whirlpool");
} catch(NoSuchAlgorithmException e) {
    // Do something on exception
}