3 ms·
It works, until it doesn't. Exceptions are the one place in Java that supports union types, if you have code that can throw both Exception1 and Exception2 then
by Nullabillity 2y ago
It works, until it doesn't. Exceptions are the one place in Java that supports union types, if you have code that can throw both Exception1 and Exception2 then Java can keep track of whether they are thrown separately:
class Exception1 extends Exception {}
class Exception2 extends Exception {}
interface ThrowingFunction {
void apply() throws Exception1, Exception2;
}
class Foo {
public void doFoo(ThrowingFunction f) throws T {
f.apply();
}
public static void main() throws Exception1, Exception2 {
new Foo().doFoo(() -> {
if (false) {
throw new Exception1();
}
if (false) {
throw new Exception2();
}
});
}
}}
However, if you pass them through a generic then they will be flattened into the closest common ancestor:
class Exception1 extends Exception {}
class Exception2 extends Exception {}
interface ThrowingFunction<T extends Throwable> {
void apply() throws T;
}
class Foo {
public <T extends Throwable> void doFoo(ThrowingFunction<T> f) throws T {
f.apply();
}
// Fails to compile, because Exception is still unhandled
public static void main() throws Exception1, Exception2 {
new Foo().doFoo(() -> {
if (false) {
throw new Exception1();
}
if (false) {
throw new Exception2();
}
});
}
}