Reputation: 2357
I'm experiencing some strange behavior but maybe I just don't completely understand how exception-handling works. I have the following piece of code:
public String encrypt(String msg, SecretKeySpec key) throws RuntimeException {
try {
System.out.println("1");
cipher.init(Cipher.ENCRYPT_MODE, key);
System.out.println("2");
...
} catch (InvalidKeyException e) {
System.out.println("3");
throw new RuntimeException("invalid key");
}
}
Upon invoking, the method throws a RuntimeException and the console output is: 1
(The cipher object is an attribute of the class the method is part of and was successfully created using Cipher.getInstance("AES", "BC")
. Here is the documentation of the init method where the program fails.)
Upvotes: 1
Views: 1741
Reputation: 1074248
The symptoms tell us that init
is throwing a RuntimeException
. Since that isn't an InvalidKeyException
, your catch
handler doesn't catch it.
Remember that although init
is only documented to throw InvalidKeyException
, it can also throw any RuntimeException
it likes. RuntimeException
doesn't have to be declared (or caught); it's an unchecked exception, that's its purpose.
Although you don't have to catch them, you can catch them if you want. Normally that's not good practice (it's normally a RuntimeException
for a good reason), but in limited cases catching it can be appropriate.
Upvotes: 3