-2

When I try to run this code in my Main class my IDE pops up and says that I'm not handling the exception I'm throwing at the beginning of my method.

public byte[] generateSalt() throws NoSuchAlgorithmException{

        // VERY important to use SecureRandom instead of just Random
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");

        // Generate a 8 byte (64 bit) salt as recommended by RSA PKCS5
        byte[] salt = new byte[8];
        random.nextBytes(salt);

        return salt;

}
Alex Day
  • 39
  • 1
  • 7
  • 2
    So what is your question? If you don't know what to do with the exception I suggest you rethrow it just like you do in this method. – Peter Lawrey Dec 29 '15 at 17:56
  • where are you calling `generateSalt`? Are you handling the exception there? Where does the compiler complain? – luk2302 Dec 29 '15 at 17:58
  • where are you calling this method, post that part – Ramanlfc Dec 29 '15 at 17:58
  • Why is it important to use s specific SecureRandom implementation. You can just use the default `SecureRandom` and it won't throw an Exception for you to handle. – Peter Lawrey Dec 29 '15 at 18:00

1 Answers1

1

if this method is throwing en exception, than every method that uses it needs to either catch that exception, or throw it as well.

If a method that uses generateSalt is not doing one of the two, then the compiler will complain about unhandled exception.

The solution is simple, on the calling method either add throws NoSuchAlgorithmException to the signature, or do this:

try {
  generateSalt();
} catch (NoSuchAlgorithmException e) {
  // do something with the exception
}
Nir Levy
  • 12,750
  • 3
  • 21
  • 38