操作异常嵌套Java

297 阅读1分钟

我偶然发现了一个读取文本文件并对其进行分析的代码库。我对异常的使用方式有点困惑。单独的班级AppFileReaderExceptionextends已定义异常,其中扩展类仅返回异常的错误消息。此外,功能getSymbol()兼用throws和try and catch block。这个error()函数也有异常处理程序,这可能导致嵌套异常!在基本的尝试和捕获应该足够的情况下,执行这样的异常处理有什么好处吗?是否有任何理由扩展异常类,将两者结合在一起?throwstry-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;
    }

}

类的扩展类。AppFileReaderException如下:

package AppName;
public class AppFileReaderException extends Exception {

    public AppFileReaderException(String msg)
    {
        super(msg);
    }
}

首先,error()方法(不是函数!)没有任何处理。它只是抛出一个异常与给定的消息。

在调用方法时,创建自己的异常类可能很有用;因此,您可以执行以下操作

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.
   }
}

也就是说,这里的系统有点奇怪。通过在error()方法时,异常的堆栈跟踪对于引发异常的所有可能位置都是相同的。而且,看起来它只是掩盖了IOException,所以我可能会转发IOException本身(如果不是,则在最终抛出的异常中包含嵌套的异常,以提供更好的调试信息)。