Java 嵌套异常处理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16633745/
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
Java Nested Exception Handling
提问by Shan
I came across a code base that read a text file and analyzes it. I am bit confused with the way the exceptions are used. A separate class AppFileReaderException
that extends
exceptions has been defined where the extended class only returns the error message for the exception. Besides, the function getSymbol()
uses both throws
and try and catch block
. The error()
function has an exception handler too which could result in nested exceptions ! Is there any advantage of doing such exception handling where the basic try and catch should be sufficient? Is there any reason to extend the exception class, combine both throws
and try-catch
block? Are these over kill or there is a good reason to have such constructs?
我遇到了一个读取文本文件并对其进行分析的代码库。我对异常的使用方式有些困惑。已定义异常的单独类AppFileReaderException
,extends
其中扩展类仅返回异常的错误消息。此外,该函数同时getSymbol()
使用throws
和try and catch block
。该error()
函数也有一个异常处理程序,这可能会导致嵌套异常!在基本的 try 和 catch 应该足够的情况下进行此类异常处理是否有任何优势?是否有任何理由扩展异常类,将两者结合起来throws
并try-catch
阻止?这些是过度杀伤还是有充分的理由拥有这样的构造?
package AppName;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
public class AppFileReader {
//
public char getSymbol() throws AppFileReaderException {
try {
//do something
} catch (Exception e) {
error("IO Error: " + fileName + "@" + currentLineNumber);
}
return somechar;
}
public void error(String errorMsg) throws AppFileReaderException {
throw new AppFileReaderException(errorMsg);
}
public AppFileReader(String fileName) throws FileNotFoundException {
reader = new LineNumberReader(new FileReader(fileName));
this.fileName = fileName;
}
}
//------------------------------------------------------------------
//------------------------------------------------ ------------------
The extended class for the AppFileReaderException
is as follows:
的扩展类AppFileReaderException
如下:
package AppName;
public class AppFileReaderException extends Exception {
public AppFileReaderException(String msg)
{
super(msg);
}
}
回答by SJuan76
First, the error()
method (not function!) does not have any handling. It just throws an exception with the given message.
首先,error()
方法(不是函数!)没有任何处理。它只是用给定的消息抛出异常。
Creating your own exception classes may be useful when calling the methods; so you can do something like
调用方法时,创建自己的异常类可能很有用;所以你可以做类似的事情
public void methodThatCallsLibrary() {
try {
doSomething();
new AppFileReader().getSymbol();
doOtherSomething();
} catch (AppFileReaderException afre) {
// handling specific to appFileReader
} catch (Exception e) {
// handling related to the rest of the code.
}
}
That said, the system here is a Little odd. By creating the exception in the error()
method, the stacktrace of the exception is the same for all the possible places where an exception is raised. Also, it looks like that it just masks IOException, so I would probably go for forwarding the IOException itself (and, if not, include the nested exception in the exception that is finally thrown, to give a better debugging information).
也就是说,这里的系统有点奇怪。通过在error()
方法中创建异常,异常的堆栈跟踪对于引发异常的所有可能位置都是相同的。此外,看起来它只是掩盖了 IOException,所以我可能会转发 IOException 本身(如果没有,在最终抛出的异常中包含嵌套异常,以提供更好的调试信息)。
回答by Bathsheba
Deriving your own exceptions from the base exception class is a very good idea since
从基本异常类派生自己的异常是一个很好的主意,因为
1) you can deal with different exception objects separately.
1)可以分别处理不同的异常对象。
2) functions often have "throws ..." suffixed to them which tells the caller what exceptions to expect. This helps program stability.
2) 函数通常有“throws ...”后缀,它告诉调用者期望什么异常。这有助于程序稳定性。
Remember that java has a multicatch exception syntax:
请记住,java 有一个 multicatch 异常语法:
Catch (exception1 | exception2 | ... e) where e is the caught object. Use this if you want to deal with such exception types equivalently.
Catch (exception1 | exception2 | ... e) 其中 e 是被捕获的对象。如果您想等效地处理此类异常类型,请使用此选项。
回答by Danubian Sailor
The system of checked and unchecked exceptions in Java was experimental, but the most programmers believe this was not a good concept. Additionally, the checked exception hierarchy is bad designed, for example, if you do something with reflection, you have to catch 4 or 5 separate exceptions.
Java 中检查和未检查异常的系统是实验性的,但大多数程序员认为这不是一个好概念。此外,检查异常层次结构的设计很糟糕,例如,如果您使用反射进行某些操作,则必须捕获 4 或 5 个单独的异常。
In practice, almost every bean code in modern web application invokes some functions that do something with IO, SQL (and probably reflection) so with checked exception system, you'd have a lot of exceptions to handle or to add to function signature.
在实践中,几乎现代 Web 应用程序中的每个 bean 代码都会调用一些对 IO、SQL(可能还有反射)执行某些操作的函数,因此使用检查异常系统,您将有很多异常要处理或添加到函数签名中。
A programming model for Java, proposed for example in Spring, is to handle exceptions transparently. You have an interface for service, the implementation can use WebService, SQL database or anything else. How can you know what exceptions to handle and how? Therefore, you provide your own exception hierarchy that you can handle in single place.
例如在 Spring 中提出的 Java 编程模型是透明地处理异常。你有一个服务接口,实现可以使用 WebService、SQL 数据库或其他任何东西。您怎么知道要处理哪些异常以及如何处理?因此,您提供自己的异常层次结构,您可以在一个地方处理。
Spring also wraps all exceptions in NestedRuntimeException
.
Spring 还将所有异常包装在NestedRuntimeException
.
You can also handle exceptions in aspectsor filters. In that case the exceptions should be fully transparent for your business code. You separate fully exception handling from normal processing.
您还可以处理方面或过滤器中的异常。在这种情况下,异常应该对您的业务代码完全透明。您将完全异常处理与正常处理分开。