Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to return in a try block?

Tags:

java

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?


1 Answers

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.

like image 91
Marcin Pietraszek Avatar answered Sep 07 '25 16:09

Marcin Pietraszek