捕获多个异常并重新抛出一般异常 [英] Catching several exceptions and rethrowing a general exception

查看:173
本文介绍了捕获多个异常并重新抛出一般异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用反射将一些数据添加到第三方库中某个类的私有变量中。一路上可以抛出大约四个不同的异常。它们都与反射有关,并且都不太可能发生。我正在对涉及的类和变量的名称进行硬编码。我不太可能收到任何未找到的类或未找到字段的错误,除非该库有一天升级了并且已发生重大变化。

I'm using reflection to add some data to a private variable inside a class from a third-party library. Along the way there are about four different Exceptions that can be thrown; all of them are related to reflection, and all of them are very unlikely to occur. I'm hardcoding the name of the class and variable involved. I'm unlikely to receive any class not found or field not found errors, unless the library gets upgraded some day and has changed significantly.

我宁愿不声明所有这些异常中有四个可供我的呼叫者处理。他可能永远也看不到他们。我只想抓住所有这些,然后抛出另一个异常,说发生了Java反射错误;很可能库已以与该方法不兼容的方式进行了升级和更改。我是否可以抛出一个标准的Java异常,该异常指示一般的反射错误?我应该定义自己的吗?还是最好只声明此方法可以引发所有可能的反射异常?

I'd rather not declare all four of these exceptions for my caller to handle. He's likely to never see them. I'd like to just catch all of these and throw another exception to say "A Java reflection error has occured; it is likely that the library has been upgraded and changed in a way incompatible with this method." Is there a standard Java Exception I can throw that indicates just a general reflection error? Should I define my own? Or would it be best to just declare that this method can throw all of the possible reflection exceptions?

推荐答案

您可以将所有如果您从不希望发生异常,则会将这些异常转为AssertionError。如果要处理特定的异常,可以解包
InvocationTargetException。
如果您想抛出方法抛出的实际异常而不是InvocationTargetException,则可以使用此技巧,但它可能比有用的更令人困惑。

You can turn all the Exceptions into an AssertionError if you never expect them to occur. InvocationTargetException can be unwrapped if you want to deal with a specific exception. If you want to throw the actual exception thrown by the method rather than InvocationTargetException you can use this trick, but it may be more confusing than useful

} catch (InvocationTargetException e) {
    // Throw any exception in the current thread (even if it is a checked exception)
    Thread.currentThread().stop(e.getCause());
}

这篇关于捕获多个异常并重新抛出一般异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆