javaexceptionruntimeexception

Compile error catching exceptions in the same catch clause


I have two RuntimeExceptions as you can see below:

@Getter
@RequiredArgsConstructor
public class MyCustomRuntimeException1 extends RuntimeException {

    private final String message;
    private final int code;
}

@Getter
@RequiredArgsConstructor
public class MyCustomRuntimeException2 extends RuntimeException {

    private final String message;
    private final int code;
}

Then I have my doSomethingMethod where I catch them in the same catch clause:

public void doSomething() {

[....]
[....]
 
    try {

         [....]
         [....]    

    } catch (MyCustomRuntimeException1 | MyCustomRuntimeException2 ex) {
            log.error("!! doSomething: An error occurred", ex);
            var code = ex.getCode();
            var message = ex.getMessage();

            [......]
            [......]
    }
}

I'm receiving a compile-time error that says Cannot resolve method 'getCode' in 'RuntimeException' on the following line:

var code = ex.getCode();

On the other hand, this snippet code works properly:

public void doSomething() {

[....]
[....]
 
    try {

         [....]
         [....]    

    } catch (MyCustomRuntimeException1 ex) {
            log.error("!! doSomething: An error occurred", ex);
            var code = ex.getCode();
            var message = ex.getMessage();

            [......]
            [......]

    } catch (MyCustomRuntimeException2 ex) {
            log.error("!! doSomething: An error occurred", ex);
            var code = ex.getCode();
            var message = ex.getMessage();

            [......]
            [......]
    }
}

Solution

  • I believe what happens here, when you have a multi-catch clause, is that the inferred type of the exception parameter, ex in your case, is the nearest common superclass of the exceptions listed in the multi-catch. I couldn't find this explicitly documented in the language reference, but it is implied in at least one place. See the example at the end of 14.20. the try statement

    So the nearest common superclass of your two exception classes is RuntimeException, which of course does not have a getCode() method.

    As @VasilyLiakovsky suggests in a comment, you could create an abstract intermediate class that defines the common methods you'd like to share.