Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I avoid getting "Missing return statement" when calling a method that throws an exception, from within another method?

Tags:

java

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?

like image 637
eparvan Avatar asked May 29 '19 12:05

eparvan


2 Answers

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.

like image 186
minus Avatar answered Nov 17 '22 23:11

minus


Next to the great answer already provided by Slawomir Chodnicki, here's another suggestion.

Change your callMethodThatAlwaysThrowsUncheckedExceptions() which somewhere throws an Exception into a factory method. E.g: change this:

// somewhere in callMethodThatAlwaysThrowsUncheckedExceptions
throw new MyException();

To:

return new MyException();

That way you can call that method like this:

throw callMethodThatAlwaysThrowsUncheckedExceptions();

And thus will help the compiler to see that this is the last statement of that execution branch.

This also works greatly with different exceptions, just return instead of throw

like image 9
Lino Avatar answered Nov 17 '22 23:11

Lino