重构此方法以抛出最多一个已检查的异常,而不是:java.security.GeneralSecurityException、java.io.IOException

问题描述 投票:0回答:1

我想达到的目标:

有方法获得

javax.net.ssl.KeyManagerFactory;

我尝试了什么:

代码如下:

public final KeyManagerFactory getKeyManagerFactory() throws GeneralSecurityException, IOException {
        final var keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        try (InputStream file = new FileInputStream(keyStoreLocation)) {
            final var keyStore = KeyStore.getInstance(PKCS12);
            keyStore.load(file, keyStorePassword.toCharArray());
            keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
            return keyManagerFactory;
        }
    }

问题:

SonarQube 扫描后,我得到

Refactor this method to throw at most one checked exception instead of: 

注:

它曾经有各种各样的例外

UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException CertificateException, IOException, NoSuchAlgorithmException FileNotFoundException

我尽我所能重构,但仍然留下

Refactor this method to throw at most one checked exception instead of: java.security.GeneralSecurityException, java.io.IOException

问题:

如何重构它以在不使用

throws Exception
的情况下最多抛出一个已检查的异常,这将触发另一个 SonarQube 问题?

java sonarqube refactoring
1个回答
1
投票

SonarQube 注释意味着该方法有可能抛出多个异常。这意味着处理此方法可能在调用它的任何地方抛出的异常的时间可能会更长(并且可能会产生重复的代码)。

为了优化此代码,您可以在方法本身中处理这两个异常并抛出另一个异常。

您可以创建一个自定义

KeyManagerFactoryException
(或更相关的是,与您的班级名称相关的例外)。可以产生异常的代码应该用 try-catch 块 包围,并且两个异常都可以在那里处理。

public final KeyManagerFactory getKeyManagerFactory() throws KeyManagerFactoryException {
    final var keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    try (InputStream file = new FileInputStream(keyStoreLocation)) {
        final var keyStore = KeyStore.getInstance(PKCS12);
        keyStore.load(file, keyStorePassword.toCharArray());
        keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
        return keyManagerFactory;
    } catch (IOException ex) {
        // some logging or extra handling of the error

        throw new KeyManagerFactoryException("Your exception message documenting the error", ex);
    } catch (GeneralSecurityException ex) {
        // some logging or extra handling of the error

        throw new KeyManagerFactoryException("Your exception message documenting the error", ex);
    }
}

你的自定义异常类看起来像:

public class KeyManagerFactoryException extends Exception {
    public KeyManagerFactoryException(String message, Throwable cause) {
        super(message, cause);
    }
}

因此,您的方法将只能引发单一类型的异常。

© www.soinside.com 2019 - 2024. All rights reserved.