大家好,我一直在为GUI设计一些按钮,我决定实现一些以前的代码。

但是,尝试编译时出现错误。在我的代码的141行中(特别是最后一个按钮),我被告知我有一个未报告的IOException,必须被捕获或声明为抛出。

我的代码如下:

public void actionPerformed(ActionEvent ae) {
    if ((ae.getSource() == button5) && (!connected)) {
        try {
            s = new Socket("127.0.0.1", 2020);
            pw = new PrintWriter(s.getOutputStream(), true);
        } catch (UnknownHostException uhe) {
            System.out.println(uhe.getMessage());
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
        }
        connected = true;
        t = new Thread(this);
        //b.setEnabled(false);
        button5.setLabel("Disconnect");
        t.start();
    } else if ((ae.getSource() == button5) && (connected)) {
        connected = false;
        try {
            s.close(); //no buffering so, ok
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
        }
        //System.exit(0);
        button5.setLabel("Connect");
    } else {
        temp = tf.getText();
        pw.println(temp);
        tf.setText("");
    }
    if (ae.getActionCommand().equals("Save it")) {
        Scanner scan = new Scanner(System.in);
        try {
            PrintWriter pw = new PrintWriter(new FileWriter(new File("test.txt")));
            for (;;) {
                String temp = scan.nextLine();
                if (temp.equals("")) {
                    break;
                }
                pw.println(temp);
            }
            pw.close();
        } catch (IOException ioe) {
            System.out.println("IO Exception! " + ioe.getMessage());
        }
    } else if (ae.getActionCommand().equals("Load it")) {
        Scanner scan = new Scanner(System.in);
        try {
            BufferedReader br = new BufferedReader(new FileReader(new File("test.txt")));
            String temp = "";
            while ((temp = br.readLine()) != null) {
                System.out.println(temp);
            }
            br.close();
        } catch (FileNotFoundException fnfe) {
            System.out.println("Input file not found.");
        } catch (IOException ioe) {
            System.out.println("IO Exception! " + ioe.getMessage());
        }
    } else if (ae.getActionCommand().equals("Clear it")) {
        ta.setText("");
    } else {
        PrintWriter pw = new PrintWriter(new FileWriter(new File("test.txt")));

    }
}

最佳答案

只需将try / catch块添加到以下代码(发布内容的结尾):

else{
PrintWriter pw = new PrintWriter (
            new FileWriter(
            new File("test.txt")));

}}


像这样:

else{
        try{
            PrintWriter pw = new PrintWriter (new FileWriter(new File("test.txt")));
        } catch (Exception e) {
            e.printStackTrace();
        }
}}

关于java - Java未报告的异常使我感到困惑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30199449/

10-10 22:35