Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 重构代码以引发RuntimeException而不是返回值_Java_Refactoring_Runtimeexception - Fatal编程技术网

Java 重构代码以引发RuntimeException而不是返回值

Java 重构代码以引发RuntimeException而不是返回值,java,refactoring,runtimeexception,Java,Refactoring,Runtimeexception,由于代码重复,我需要重构现有代码 以下结构在疯狂类中出现10次以上: public MyType doSomething(...) { MyType myType = ........ if (myType == null) { final String message = "..."; LOGGER.error(message); throw new XxxRuntimeException(message)); }

由于代码重复,我需要重构现有代码

以下结构在疯狂类中出现10次以上:

public MyType doSomething(...) {
    MyType myType = ........
    if (myType == null) {
        final String message = "...";
        LOGGER.error(message);
        throw new XxxRuntimeException(message));
    }
    return myType;
}
我想重构
LOGGER.error
向如下新方法抛出新的RuntimeException
行:

private void logErrorAndThrowRuntimeException(String message) {
    LOGGER.error(message);
    throw new XxxRuntimeException(message));
}
问题是重构后,
if
contion中没有返回值

我无法将异常类型从
RuntimeException
更改为
exception
,因为此应用程序具有疯狂的逻辑,需要抛出RuntimeExceptin


您知道如何将这两行代码重构为新方法并保持原始方法的逻辑不变吗?

声明一个可丢弃的返回类型:

private XxxRuntimeException logErrorAndThrowRuntimeException(String message) {
    LOGGER.error(message);
    // You can throw here, or return if you'd prefer.
    throw new XxxRuntimeException(message));
}
然后您可以在调用站点抛出此消息,以指示if主体无法正常完成:

public MyType doSomething(...) {
    MyType myType = ........
    if (myType == null) {
        final String message = "...";
        throw logErrorAndThrowRuntimeException(message);
    }
    return myType;
}

声明可丢弃的返回类型:

private XxxRuntimeException logErrorAndThrowRuntimeException(String message) {
    LOGGER.error(message);
    // You can throw here, or return if you'd prefer.
    throw new XxxRuntimeException(message));
}
然后您可以在调用站点抛出此消息,以指示if主体无法正常完成:

public MyType doSomething(...) {
    MyType myType = ........
    if (myType == null) {
        final String message = "...";
        throw logErrorAndThrowRuntimeException(message);
    }
    return myType;
}