在我的程序中,我有一个内部侦听器类。它的目的是打开一个文件并从中读取数据:
// This declaration is outside of the inner class.
SimulationModel model;
// End of declarations.
class OpenListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFileChooser fileOpen = new JFileChooser();
fileOpen.showOpenDialog(gui);
if (fileOpen.getSelectedFile() != null) {
try (FileInputStream fis = new FileInputStream(fileOpen.getSelectedFile());
ObjectInputStream ois = new ObjectInputStream(fis)) {
Object modelObject;
modelObject = ois.readObject();
model = (SimulationModel) modelObject;
consolePanel.printToConsole("File opened.\n\n");
// Do stuff with model object of SimulationModel class.
// About 10 lines of code, mostly reading from model.
} catch (IOException | ClassNotFoundException ex) {
consolePanel.printToConsole("Error during file opening.\n\n");
}
}
}
}
我注释掉的代码行 (// Do stuff (...)) 不会抛出任何异常,但如果文件读取不正确,则不应执行这些行。这就是为什么我将 I/O 代码和注释掉的代码都放在 try 块中的原因。但是,我怀疑在 try 块中放置不会引发任何异常的代码。
是否有更优雅的方法来确保注释掉的代码不会执行,但仅在执行 I/O 操作的代码中检查异常?