java - SONAR 问题 "main"不应该是 "throw"任何 JAVA 7

标签 java exception sonarqube program-entry-point throws

我们有这个代码。 SONAR 提示 main() 函数。 “main”不应该“抛出”任何东西

main 方法没有理由抛出任何东西。毕竟,什么能捕获它呢? 相反,该方法本身应该优雅地处理可能出现的任何异常,附加尽可能多的上下文信息,并执行任何必要的日志记录或用户通信。

问:添加 catch(IOException e) {} 是否可以缓解此问题?

public class EncryptionHelper {

    private static final int NO_OF_ARGUMENTS = 3;

    /**
     * Ctor
     */
    protected EncryptionHelper() {
        // Empty Ctor
    }

    /**
     * Main
     * 
     * @param args
     * 
     *            0 - Input text to be encrypted or decrypted 
     *            1 - Encrypt/Decrypt [0-Encrypt, 1-Decrypt]
     *            2 - File to write the output
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        if (args.length != NO_OF_ARGUMENTS) {
            throw new IllegalArgumentException("Expected 3 arguments to encrypt/decrypt.");
        }
        OutputStreamWriter fw = null;
        Crypto crypto = CryptoFactory.getCrypto(CryptoType.KBE);
        String en = "";
        if ("0".equals(args[1])) {
            en = crypto.encryptString(args[0]);
        } else {
            en = crypto.decryptString(args[0]);
        }
        try {
            fw = new OutputStreamWriter(new FileOutputStream(args[2]), Charset.forName("UTF-8"));
            fw.write(en);
        } finally {
            if (fw != null) {
                fw.close();
            }

        }
    }
}

最佳答案

Would adding a catch(IOException e) {} mitigate this issue?

不!我认为,这是最糟糕的解决方案。顺便说一句,如果你这么写,Sonar 会提示空的 catch block - 所以一个问题解决了,结果就会出现一个新问题。

这更多的是一个设计错误。

当您想要打开一个不存在的文件时,想想 Microsoft Word 或 LibreOffice。 (例如,您在打开的对话框中写入:notExistingFile.doc 并按 Enter)。如果不存在名为 notExistingFile.doc 的文件,则会引发某种异常(基于他们使用的编程语言/框架)。

但是,他们不会使应用程序崩溃并抛出异常,而是处理这种情况 - 弹出一个窗口,通知您文件不存在。

如果这是一个测试应用程序或一些私有(private)项目,您 100% 确定该文件存在,那么我不会对此采取任何措施。但如果它是一个公共(public)项目,您应该以某种方式处理异常:编写有关丢失文件的日志,通知用户丢失文件(建议问题的一些解决方案)等。

如果您希望问题消失,您应该将其标记为已解决(或隐藏该问题,有一些方法可以解决)。如果您想从 java 代码解决这个问题,您应该编写以下内容:

try {
    // some methods that throw IOException
} catch (IOException ignored) {
    // if you call your variable ignored, Sonar won't complain about it
    // but you should provide some information about this, why did you ignore that exception
    // for developers looking at this code later.
}

关于java - SONAR 问题 "main"不应该是 "throw"任何 JAVA 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34908828/

相关文章:

java - 将数组中的整个数组内容转入

java - Java 中 HashMap 中一个键的多个值

c# - 用于空值的适当异常

scala - 在 Scala 中结合 Futures (Twitter) 和两者

SonarQube 5.1 显示细节时没有问题

python - Sonar 未能获得 pylint 结果

java - 如何使用 Log4j 创建基于进程的日志文件?

java - 如何检索 Java 供应商信息

c++ - 哪个 vector 引发索引超出范围异常?

active-directory - 哪些 SonarQube 插件支持 SSO?