我遇到了一个读取文本文件并分析它的代码库。我对使用例外的方式感到困惑。一个单独的类AppFileReaderException
,extends
异常已定义,其中扩展类仅返回异常的错误消息。此外,功能getSymbol()
同时使用throws
和try and catch block
。 error()
函数也有一个异常处理程序,可能会导致嵌套异常!在基本尝试和捕获应该足够的情况下进行这种异常处理是否有优势?是否有任何理由扩展异常类,结合throws
和try-catch
块?这些过度杀手还是有充分理由拥有这样的结构?Java嵌套异常处理
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);
}
}