我很好奇在try块中是否应该有return语句的最佳实践。
我有一个方法调用了一个返回整数并可能抛出IllegalArgumentException异常的服务方法。有两种方法可以实现:
第一种:
public int getLookupStatus(String lookupType)
{
try
{
return this.lookupService.getCountOfLookupRecords(lookupType);
}
catch(IllegalArgumentException ex)
{
throw new RestException();
}
}
第二点:
public int getLookupStatus(String lookupType)
{
int count;
try
{
count = this.lookupService.getCountOfLookupRecords(lookupType);
}
catch(IllegalArgumentException ex)
{
throw new RestException();
}
return count;
}
在第二种方法中,count变量似乎是不必要的,但对我而言,第一种方法似乎是错误的。是否有任何特定的原因来支持其中一种方法?
count
是一个原始类型。如果它是像String
这样的东西,就不行了。 - Vivin Paliathcount =
行时进行初始化。如果该行未能完成,则编译器知道throw New RestException()
将会发生,从而阻止了return count
的执行。 - yshavit