SonarQube要求移除main方法throws Exception子句,求修复方案
Fixing SonarQube's "Remove throws Exception from main" Issue
Hey there! Let's break down this SonarQube alert and fix your code properly, with clear reasoning behind each change.
Why SonarQube is flagging this
- Throwing
Exceptionfrom themainmethod is considered lazy and unmaintainable. It catches all exceptions (both checked and runtime) and hands them off to the JVM to handle with a raw stack trace. This hides potential bugs and makes your program's error behavior unpredictable. - SonarQube enforces this rule to push for explicit error handling: you should catch specific exceptions and handle them gracefully instead of passing the buck up to the system.
How to fix it
Instead of declaring throws Exception, wrap the code that can throw exceptions in a try-catch block. This lets you control how errors are presented to the user and keeps your code clean.
Step-by-step changes to the main method:
- Remove
throws Exceptionfrom the method signature. - Wrap the encryption/decryption logic in a
tryblock (all the code that creates theEncryptorand calls its methods). - Add a
catchblock to capture any exceptions, then print a user-friendly error message (plus debug details if needed). - Keep the existing logic for invalid input (the
elseclause) as-is.
Fixed Full Encryptor Class
package xxx; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.Key; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; public class Encryptor { private static final String ALGORITHM = "AES"; private static final String defaultSecretKey = "xxx"; private Key secretKeySpec; public Encryptor() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException { this(null); } public Encryptor(String secretKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException { this.secretKeySpec = generateKey(secretKey); } public String encrypt(String plainText) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8")); return asHexString(encrypted); } public String decrypt(String encryptedString) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); byte[] original = cipher.doFinal(toByteArray(encryptedString)); return new String(original); } private Key generateKey(String secretKey) throws UnsupportedEncodingException, NoSuchAlgorithmException { if (secretKey == null) { secretKey = defaultSecretKey; } byte[] key = (secretKey).getBytes("UTF-8"); MessageDigest sha = MessageDigest.getInstance("SHA-256"); key = sha.digest(key); key = Arrays.copyOf(key, 16); // use only the first 128 bit KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(256); // 192 and 256 bits may not be available return new SecretKeySpec(key, ALGORITHM); } private final String asHexString(byte buf[]) { StringBuffer strbuf = new StringBuffer(buf.length * 2); int i; for (i = 0; i < buf.length; i++) { if (((int) buf[i] & 0xff) < 0x10) { strbuf.append("0"); } strbuf.append(Long.toString((int) buf[i] & 0xff, 16)); } return strbuf.toString(); } private final byte[] toByteArray(String hexString) { int arrLength = hexString.length() >> 1; byte buf[] = new byte[arrLength]; for (int ii = 0; ii < arrLength; ii++) { int index = ii << 1; String l_digit = hexString.substring(index, index + 2); buf[ii] = (byte) Integer.parseInt(l_digit, 16); } return buf; } public static void main(String[] args) { if (args.length == 1) { String plainText = args[0]; try { Encryptor aes = new Encryptor(); String encryptedString = aes.encrypt(plainText); // Verify decryption works String decryptedString = aes.decrypt(encryptedString); System.out.println("Original Password: " + plainText + " and Encrypted Password: " + encryptedString); } catch (Exception e) { // Handle errors gracefully for users System.err.println("Error processing your input: " + e.getMessage()); // Optional: Print stack trace for debugging purposes e.printStackTrace(); } } else { System.out.println("USAGE: java AES string-to-encrypt"); } } }
Key details about the fix
- We moved all code that can throw exceptions into a
tryblock: creating theEncryptorinstance, callingencrypt(), and callingdecrypt(). - The
catch (Exception e)block catches all possible exceptions from those operations. For a production app, you could split this into multiplecatchblocks to handle specific exceptions (likeInvalidKeyExceptionorNoSuchAlgorithmException) with tailored messages, but this simplified approach works well for a utility main method. - We use
System.errfor error messages to separate them from regular output, which is a standard best practice.
内容的提问来源于stack exchange,提问作者Martin Fric
相关产品推荐
相关产品推荐

