I'm puzzled of the following compiler error "java.lang.Throwable.getMessage() is defined in an inaccessible class or interface" when I catch multiple exceptions, which inherit from same package protected abstract class.
The Maven build fails (Maven 3.8.x on Win/Mac/Unix ), compiling it with javac works.
But if I:
- only catch a single exception -> compiles
- catch multiple exceptions (which inherit from same package protected abstract class) and add another exception (i.e. RuntimeException) -> compiles
Can anyone explain this behavior to me?
Main.java:
package com.foo.service;
import com.foo.utils.ExceptionA;
import com.foo.utils.ExceptionB;
public class Main {
public static void main(String[] args) {
try {
if (true) {
throw new RuntimeException("RuntimeException");
}
if(true) {
throw new ExceptionA("ExceptionA");
}
if (true) {
throw new ExceptionB("ExceptionA");
}
}
catch (ExceptionA | ExceptionB e) { // <- won't compile: "Cannot access 'getMessage()' in 'java.lang.Throwable'"
e.getMessage();
}
// catch (ExceptionA e) { // <- compiles
// e.getMessage();
// }
// catch (ExceptionA | ExceptionB | RuntimeException e) { // <- compiles
// e.getMessage();
// }
}
}
AbstractException.java:
package com.foo.utils;
class AbstractException extends Exception {
protected AbstractException(final String message){
super(message);
}
}
ExceptionA.java:
package com.foo.utils;
public class ExceptionA extends AbstractException {
public ExceptionA(String message) {
super(message);
}
}
ExceptionB.java:
package com.foo.utils;
public class ExceptionB extends AbstractException {
public ExceptionB(String message) {
super(message);
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>foo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>