Best Practice
Scenario 1: A method logic throwing multiple exceptions
public static String encrypt(String plainText, String secretKey) throws InvalidAlgorithmParameterException,
NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException,
IOException, BadPaddingException, NoSuchProviderException, InvalidKeyException {
// Some encryption logic
}Pros
Cons
Best practice is to throw a custom exception in this scenario
public class EncryptionException extends Exception {
public EncryptionException(String message, Throwable cause) {
super(message, cause);
}
}
public static String encrypt(String plainText, String secretKey) throws EncryptionException {
try {
// encryption logic here
} catch (InvalidAlgorithmParameterException | NoSuchPaddingException | IllegalBlockSizeException |
NoSuchAlgorithmException | IOException | BadPaddingException |
NoSuchProviderException | InvalidKeyException e) {
throw new EncryptionException("Encryption failed", e);
}
}Last updated