How to avoid compilation error: missing return statement

eparvan :

I have a method that handles different error codes and always throws unchecked exception. This method is used in many places across the class. When I try to call it inside another method that has not void return type as shown below:

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

java compiler says that the method is missing return statement.

Only two options come to my mind how to solve this problem:

  • replace method call with its content
  • add a return statement just after method call that returns an empty object

However I don't really like any of these options: the first one because of code duplication and the second one because of the need to write code that will never be executed.

Is there any other way to solve this problem?

minus :

Just swap around the terms, you'll never get to return if the method throws.

 if(!success){
   callMethodThatAlwaysThrowsUncheckedExceptions();
 } 

 return result;

Or even

 callMethodThatAlwaysThrowsUncheckedExceptions(succes);
 return result;

Just check the success condition in your throwing method.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=84324&siteId=1