在我正在处理的一个项目中,我发现了一个类,它用一些复杂的异常处理包装了其父类的所有方法。 它看起来类似于这样:
public void method1() throws ExceptionA {
String exceptionString = "";
try {
super.method1();
} catch (ExceptionA e) {
exceptionString = // <convert the exception to string in an elaborate way>
throw e;
} finally {
// <an elaborate logger call which uses value of exceptionString>
}
}
public void method2() throws ExceptionB, ExceptionC {
String exceptionString = "";
try {
super.method2();
} catch (ExceptionB | ExceptionC e) {
exceptionString = // <convert the exception to string in elaborate way>
throw e;
} finally {
// <an elaborate logger call which uses value of exceptionString>
}
}
// ... <a bunch of other methods like this>
我当即想到:“哇,如果有一个通用的包装器,在每个方法中只需调用它,那将会多么方便。这个类会短小十倍!”
于是我开始动手。
这就是我卡住的地方:
private interface ThrowingMethod<E extends Exception> {
void run() throws E;
}
public <E extends Exception> void wrapMethod(ThrowingMethod<E> method) throws E {
String exceptionString = "";
try {
method.run();
} catch (Exception e) {
exceptionString = // <convert the exception to string in an elaborate way>
throw e;
} finally {
// <an elaborate logger call which uses value of exceptionString>
}
}
public void method1() throws ExceptionA {
wrapMethod(super::method1); // works
}
public void method2() throws ExceptionB, ExceptionC {
wrapMethod(super::method2); // Error in Eclipse: "Unhandled exception type Exception"
}
// ... <a bunch of other methods like this>
总结一下,这种方法适用于只抛出一种已检查异常的方法。当方法抛出多个已检查异常时,Java 认为异常类型是 Exception
。
我尝试为 ThrowingMethod
和 wrapMethod
添加更多的泛型参数,但它并没有改变任何东西。
我如何才能让一个函数式接口处理多个泛型异常?
method1
仍然有效,而包装method2
仍然默认为Exception
。所以这不起作用,除非你建议我为每个可能的异常数量制作单独的包装器,但这将违背这个练习的目的,即使代码更短。 - Piotr Siupainterface ThrowingMethod<E extends Exception>
,而不是interface <E extends Exception> ThrowingMethod
。此外,没有必要将接口声明为static
。这总是被隐含的。 - Holgerjavac
没有任何区别。 - Holger