You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 Exception from the main method 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:

  1. Remove throws Exception from the method signature.
  2. Wrap the encryption/decryption logic in a try block (all the code that creates the Encryptor and calls its methods).
  3. Add a catch block to capture any exceptions, then print a user-friendly error message (plus debug details if needed).
  4. Keep the existing logic for invalid input (the else clause) 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 try block: creating the Encryptor instance, calling encrypt(), and calling decrypt().
  • The catch (Exception e) block catches all possible exceptions from those operations. For a production app, you could split this into multiple catch blocks to handle specific exceptions (like InvalidKeyException or NoSuchAlgorithmException) with tailored messages, but this simplified approach works well for a utility main method.
  • We use System.err for error messages to separate them from regular output, which is a standard best practice.

内容的提问来源于stack exchange,提问作者Martin Fric

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 21:23:10