假设我有一个类应用程序,我在其中进行错误处理,并且在这个特定的类上进行错误处理
try {
layermethod();
} catch (IOException e) {
Message.fileNotFound(filename);
}
layermethod()
属于 Layer
类,它是一个“掩码”类,我用它来将信息从应用程序传递到核心应用程序并传递到对象中。
因此在Class层中layermethod()
仅定义为
public void layermethod(Parser _parser) {
_parser.throwmethod(_interpreter);
}
只有在解析器类中,我才有实际抛出异常的方法
public void throwmethod(Parser _parser) throws IOException {
// method implementation
}
不幸的是,我收到了错误
error: unreported exception IOException; must be caught or declared to be thrown
_parser.throwmethod(_parser);
^
因为我没有捕获图层类上的异常。
有什么方法可以只在 App 类上进行错误处理(捕获异常)?假设我无法放弃图层类
最佳答案
你有两个选择。您也可以重构 Layer.layermethod()
以引发 IOException
:
public void layermethod(Parser _parser) throws IOException {
_parser.throwmethod(_interpreter);
}
或者,您可以在上述方法中显式添加一个 try catch block :
public void layermethod(Parser _parser) {
try {
_parser.throwmethod(_interpreter);
} catch (IOException e) {
// handle exception here
}
}
鉴于您似乎希望将异常引入到 App
类中,前一个选项可能就是您想要的。
关于java - 捕获方法内部方法抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40711774/