将已检查异常包装到 Java 中的未检查异常中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/484794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Wrapping a checked exception into an unchecked exception in Java?
提问by James McMahon
I have this factory method in java:
我在java中有这个工厂方法:
public static Properties getConfigFactory() throws ClassNotFoundException, IOException {
if (config == null) {
InputStream in = Class.forName(PACKAGE_NAME).getResourceAsStream(CONFIG_PROP);
config = new Properties();
config.load(in);
}
return config;
}
And I want to transform the two checked exceptions into unchecked exceptions. What is the best way to go about this?
并且我想将两个受检异常转化为非受检异常。解决这个问题的最佳方法是什么?
Should I just catch the exception and throw a new RuntimeException using the caught exception as the inner exception?
我应该捕获异常并使用捕获的异常作为内部异常抛出一个新的 RuntimeException 吗?
Is there a better way to do this or should I even be attempting to do this in the first place?
有没有更好的方法来做到这一点,或者我应该首先尝试这样做吗?
EDIT:
Just to clarify. These exceptions will be fatal, as the configuration file is essentially to the operation of the program and all exception will be caught and logged at the top level of my program.
编辑:
只是为了澄清。这些异常将是致命的,因为配置文件本质上是程序的运行,所有异常都将被捕获并记录在我的程序的顶层。
My purpose is to avoid an unnecessary throws exception, exception added to the signature of every method that calls my factory.
我的目的是避免不必要的抛出异常,异常添加到调用我的工厂的每个方法的签名中。
采纳答案by Eddie
A RuntimeException
should be used only when the client cannot recover from whatever the problem is. It is occasionally appropriate to do what you are talking about, but more often it is not appropriate.
RuntimeException
仅当客户端无法从任何问题中恢复时才应使用A。偶尔做你所说的事情是合适的,但更多时候是不合适的。
If you are using a JDK >= 1.4, then you can do something like:
如果您使用的是 JDK >= 1.4,那么您可以执行以下操作:
try { // Code that might throw an exception } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); }
and the rethrown RuntimeException
will have the original cause included inside it. This way, someone at the top of the thread catching the RuntimeException
-- your threads do catch RuntimeException
so they don't just silently die, right? -- can at least print out the FULL stack trace of the cause.
并且重新抛出的RuntimeException
将包含原始原因。这样,线程顶部的某个人会捕获RuntimeException
- 您的线程确实会捕获,RuntimeException
因此它们不会只是默默地死去,对吗?-- 至少可以打印出原因的完整堆栈跟踪。
But as others have said and will say, exceptions are checked for a reason. Only do this when you are positive that your clients cannot recover from the problem that you are rethrowing as an unchecked exception.
但正如其他人所说和将会说的那样,检查异常是有原因的。仅当您确定您的客户无法从您作为未经检查的异常重新抛出的问题中恢复时才这样做。
NOTE: Better than just RuntimeException
would be to use a more specific unchecked exception if one is available. For example, if the only reason your method could throw a ClassNotFoundException
is because a configuration file is missing, you could rethrow a MissingResourceException
, which is an unchecked exception but gives more information about why you are throwing it. Other good RuntimeException
s to use if they describe the problem you are rethrowing are IllegalStateException
, TypeNotPresentException
and UnsupportedOperationException
.
注意:比仅仅RuntimeException
使用更具体的未检查异常(如果可用)更好。例如,如果您的方法可能抛出 a 的唯一原因ClassNotFoundException
是配置文件丢失,您可以重新抛出 a MissingResourceException
,这是一个未经检查的异常,但提供了有关您为何抛出它的更多信息。RuntimeException
如果它们描述了您重新抛出的问题,则可以使用的其他好处是IllegalStateException
、TypeNotPresentException
和UnsupportedOperationException
。
Also note that it is ALWAYS a good idea for your threads to catch RuntimeException and at a minimum log it. At least this way you understand why your threads are going away.
另请注意,您的线程捕获 RuntimeException 并至少记录它总是一个好主意。至少通过这种方式您可以理解为什么您的线程会消失。
回答by jjnguy
You are doing it the correct way.
您正在以正确的方式进行操作。
In order to let checked exceptions pass though without being checked, you must wrap them in un-checked exceptions.
为了让已检查的异常通过而不被检查,您必须将它们包装在未检查的异常中。
Just remember, Exceptions are checked for a reason.
请记住,检查异常是有原因的。
回答by Nivas
If you want to avoid too many try - catch
es, catch both the exceptions in the factory itself and handle them there.
Perhaps return a default implementation.
如果你想避免过多的try - catch
es,在工厂本身捕获这两个异常并在那里处理它们。也许返回一个默认实现。
You haveto handle the exceptions, here or somewhere else.
您必须在此处或其他地方处理异常。
And since this is a factory, I think it is better that these exceptions are handled in the factory itself (same method or different method), and returning a default implementation.
而且由于这是一个工厂,我认为最好在工厂本身处理这些异常(相同的方法或不同的方法),并返回一个默认实现。
Anyway, the (business function) caller will have no clue on what has to be done when it encounters a ClassNotFoundException
.
无论如何,(业务功能)调用者在遇到ClassNotFoundException
.
回答by MicSim
Two points regarding exception handling best practices:
关于异常处理最佳实践的两点:
- Caller code cannot do anythingabout the exception -> Make it an unchecked exception
- Caller code will take some useful recovery actionbased on information in exception -> Make it a checked exception
- 调用者代码不能对异常做任何事情-> 使它成为未经检查的异常
- 调用者代码将根据异常中的信息采取一些有用的恢复操作-> 使其成为已检查异常
And you may throw the RuntimeException with or without inner exception, depending on what the caller can do with it. If you're not rethrowing the inner exception then you should log it in your method, if important.
并且您可以抛出带有或不带有内部异常的 RuntimeException,这取决于调用者可以用它做什么。如果您没有重新抛出内部异常,那么您应该将其记录在您的方法中(如果重要的话)。