-1

在我的程序中,我有一个内部侦听器类。它的目的是打开一个文件并从中读取数据:

// 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 操作的代码中检查异常?

4

2 回答 2

0

我会在单独的方法中分离读取文件的代码。null如果出现错误,它可以打印一条消息并返回:

class OpenListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        JFileChooser fileOpen = new JFileChooser();
        fileOpen.showOpenDialog(gui);
        if (fileOpen.getSelectedFile() != null) {
            model = readModel(fileOpen.getSelectedFile());
            if (model != null) {
                // Do stuff with model object of SimulationModel class.
            }
        }           
    }

    private static SimulationModel readModel(File file) {
        SimulationModel modelObject = null;
        try (FileInputStream fis = new FileInputStream(file);
             ObjectInputStream ois = new ObjectInputStream(fis))
        {
            modelObject = (SimulationModel) ois.readObject();
            consolePanel.printToConsole("File opened.\n\n");                
        } catch (IOException | ClassNotFoundException ex) {
            consolePanel.printToConsole("Error during file opening.\n\n");
        }
        return modelObject;
    }
}

您可能需要考虑更健壮的错误处理,而不是简单地将错误记录到控制台。

于 2013-05-05T18:17:50.943 回答
0

您可以简单地将 try-catch 块的内容放入方法调用中。此外,这在很大程度上取决于您的程序如何处理引发的异常。还能继续吗?如果不是简单的 printToConsole 可能不是正确的反应。

于 2013-05-05T18:18:04.857 回答