'Common catch block for two methods with return type?

I have two methods as :

 ApiResponse methodA(){
    try{
    .....
    .....
    }
    catch(Exception e){
   handleException(e) // getting error here as return is missing
    }
  
    }

There is methodB which does different work but same catch block as above.

private void handleException(Exception e){
 if (ex instanceof Exception_A) {
   throw new Service_Exception_A();
}

 else if (ex instanceof Exception_B) {
throw new Service_Exception_B();

}

else if (ex instanceof Exception_C) {
throw new Service_Exception_C();

}
.......
......
else{
throw ex;
}

Now I am getting the error where handleException() method is called in MethodA and Method B saying that "return statement is missing"

If i copy paste the catch block in each of method, then it works fine,but isnt java intelligent enough to see that the handleException will always throw exception, so no need of return statement in catch block of method A and method B.What am I missing here and how can I get this work?



Solution 1:[1]

You should change handleException to be something like:

    private <T> T handleException(Exception e){
        // ...
    }

this way the compiler will check that you only throw exceptions and do not return any values in the body of handleException method, because there is no way to construct a new instance of abstract type T (you can return null, but null is always an explicit escape hatch in Java).

In your methodA and methodB you should return in the catch-block:

    ApiResponse methodA(){
        try {
            ...
        } catch(Exception e) {
            return handleException(e);
        }
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Victor Nazarov