如何避免在从另一个方法中调用引发异常的方法时出现"Missing return statement"?



我有一个处理不同错误代码的方法,并且总是抛出未经检查的异常。此方法在整个类的许多位置使用。当我尝试在另一个没有 void 返回类型的方法中调用它时,如下所示:

public Object someMethod() {
   ....
   if(success){
     return result;
   } else {
      callMethodThatAlwaysThrowsUncheckedExceptions();
   }
}

Java编译器说该方法missing return statement

我想到的只有两个选项可以解决这个问题:

  • 将方法调用替换为其内容
  • 在返回空对象的方法调用之后添加一个 return 语句

但是,我不太喜欢这些选项中的任何一个:第一个是因为代码重复,第二个是因为需要编写永远不会执行的代码。

还有其他方法可以解决这个问题吗?

只需交换术语,如果方法抛出,您将永远无法返回。

 if(!success){
   callMethodThatAlwaysThrowsUncheckedExceptions();
 } 
 return result;

甚至

 callMethodThatAlwaysThrowsUncheckedExceptions(succes);
 return result;

只需检查投掷方法的成功条件即可。

除了Slawomir Chodnicki已经提供的伟大答案之外,还有另一个建议。

更改您的callMethodThatAlwaysThrowsUncheckedExceptions(),这会在某处将Exception扔到工厂方法中。例如:更改此内容:

// somewhere in callMethodThatAlwaysThrowsUncheckedExceptions
throw new MyException();

自:

return new MyException();

这样,您可以像这样调用该方法:

throw callMethodThatAlwaysThrowsUncheckedExceptions();

因此,将帮助编译器看到这是该执行分支的最后一个语句。

对于不同的例外情况,这也非常有效,只是return而不是throw

若要指示你不希望访问一行(在调用抛出方法之后(,你可以

throw new AssertionError("comment to your co-developers why this never gets reached")

我喜欢

减号的答案,但对于可能错误地认为return result;将始终执行的用户来说,它可能有点不可读(无论success的值如何(。

作为替代方案,您可以更改

void callMethodThatAlwaysThrowsUncheckedExceptions () {}

Object callMethodThatAlwaysThrowsUncheckedExceptions () {}

(无需更改方法主体(。

现在你可以写

public Object someMethod() {
    ....
    if (success) {
        return result;
    } else {
        return callMethodThatAlwaysThrowsUncheckedExceptions();
    }
}

上面的答案都不符合我对编程的品味。我找到的最接近的匹配项就在这里。受到这个链接答案的启发,我通过以下方式处理了missing return statement错误:

首先使方法的返回类型与它总是抛出的异常的返回类型相同

MyCustomRuntimeException callMethodThatAlwaysThrowsUncheckedExceptions() {
    // ....
    throw new MyCustomRuntimeException();
}

接下来,每当我们必须使方法执行失败时,只需调用上面的方法并抛出它

public Object someMethod() {
   // ....
   if (success) {
     return result;
   } else {
      throw callMethodThatAlwaysThrowsUncheckedExceptions();
   }
}

即使在具有返回类型的方法中也可以使用它void而无需显式提及throw关键字。当然,在这些地方,一些 IDE 可能会警告UnusedReturnValue但也可以抑制。

相关内容

最新更新