Search code examples
javaandroidsuppress-warnings

Is there a way to suppress the "catch branch identical" warning? Unable to use multi catch in this instance


Working on an android application with API 17 and currently needing to do some reflection to complete a task. The ReflectiveOperationException is only available for use from API 19 and up, however this is fine since I can simply catch each exception individually.

The problem is when I do, I get a warning saying the catch branches are identical and can be written using a multi-catch (or use Exception which I'd like to avoid). But when I write the catches as a multi-catch, I get the error saying I can't use the ReflectiveOperationException class due to not being API 19.

Simply put I'd like to just suppress the warning but wasn't able to find anything that matches besides just doing @SuppressWarning("all")

For context, here are the warnings/errors:

// Error: "Multi-catch with these reflection exceptions requires API level 19 (current min is 15) 
// because they get compiled to the common but new super type ReflectiveOperationException.
// As a workaround either create individual catch statements, or catch Exception."
try {
    return someMethodThatThrowsExceptions();
} catch (InstantiationException | IllegalAccessException e) {
    throw new RuntimeException(e); 
}

// Warning: 'catch' branch identical to 'InstantiationException | IllegalAccessException' branch"
try {
    return someMethodThatThrowsExceptions();
} catch (InstantiationException e) {
    throw new RuntimeException(e); 
} catch (IllegalAccessException e) {
    throw new RuntimeException(e); 
} catch (NoSuchMethodException e) {
    throw new RuntimeException(e); 
} catch (InvocationTargetException e) {
    throw new RuntimeException(e); 
} 

Edit: added all the catches I was dealing with, originally only had two


Solution

  • @SuppressWarnings("TryWithIdenticalCatches") should do the trick.