I am curious about the best practice concerning having a return statement in a try block.
I have a method that calls a service method that returns an integer and potentially throws an IllegalArgumentException. There are two ways to do this.
First:
public int getLookupStatus(String lookupType)
{
try
{
return this.lookupService.getCountOfLookupRecords(lookupType);
}
catch(IllegalArgumentException ex)
{
throw new RestException();
}
}
Second:
public int getLookupStatus(String lookupType)
{
int count;
try
{
count = this.lookupService.getCountOfLookupRecords(lookupType);
}
catch(IllegalArgumentException ex)
{
throw new RestException();
}
return count;
}
In the second approach, the count variable seems unnecessary, but the first approach seems wrong to me for some reason. Is there any particular reason to favor one over the other?
There is nothing wrong in returning value in try
block, if the IllegalArgumentException
was raised (or any other RuntimeException
) you wouln't even return anything from that method, normal execution flow of the program will be changed due to that exeption.
Pattern from second example is used in cases when resource used/instantiated in catch block needs to be closed, then in finally
clause you are handling this properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With