InvocationTargetException与UndeclaredThrowableException


InvocationTargetException

当java反射调用方抛出异常时,就会用InvocationTargetException将原异常包裹;

UndeclaredThrowableException

java动态代理时抛出的异常。当对某接口进行动态代理,接口的方法名称上未声明某类受检异常,而方法却抛出了该异常,动态代理会将该异常用UndeclaredThrowableException包裹。

由于jdk动态代理内部会调用method.invoke进行调用,当method抛出异常时,则会抛出InvocationTargetException。

由于InvocationTargetException是受检异常,当代理接口方法未标识InvocationTargetException,则抛出UndeclaredThrowableException

处理方法:

public static Throwable unwrapThrowable(Throwable wrapped) {
Throwable unwrapped = wrapped;
while (true) {
if (unwrapped instanceof InvocationTargetException) {
unwrapped = ((InvocationTargetException) unwrapped).getTargetException();
} else if (unwrapped instanceof UndeclaredThrowableException) {
unwrapped = ((UndeclaredThrowableException) unwrapped).getUndeclaredThrowable();
} else {
return unwrapped;
}
}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM