I built something I don't really understand - I don't know how it works. I've familiarized myself with this multicatch explaination article.
Consider these two exceptions and code:
public class MyException1 extends Exception {
// constructors, etc
String getCustomValue();
}
public class MyException2 extends Exception {
// constructors, etc
String getCustomValue() { return "foo"; }
}
try {
//...
} catch (MyException1|MyException2 e) {
e.getCustomValue(); // won't work, as I expected
}
I won't be able to call getCustomValue(), even though the method is the same, because inside Java the above try/catch is supposed to actually be casting the MyException1/2 to Exception (that's how I understood the docs).
However, if I introduce an interface like this:
public interface CustomValueGetter {
String getCustomValue();
}
public class MyException1 extends Exception implements CustomValueGetter /*...*/
public class MyException2 extends Exception implements CustomValueGetter /*...*/
and add it to both exceptions, Java is actually able to allow me to use that method. And then calling this is valid:
try {
//...
} catch (MyException1|MyException2 e) {
e.getCustomValue(); // does work
}
In short, my question is: what is actually happening here: (MyException1|MyException2 e).
What is e?
Is the closest superclass chosen as the type of
e? This question asks about it and that's, supposedly, the answer. If so, then why is the interface CustomValueGetter "visible" when I access e? It shouldn't be if, in my case,eis anException.And if not, if the real class is either
MyException1orMyException2why am I not simply able to call the same method available for both of those classes?Is
ean instance of a dynamically generated class which implements all common interfaces of both exceptions and is of the nearest common supperclass type?