gpt4 book ai didi

Java未报告的异常让我困惑

转载 作者:行者123 更新时间:2023-11-30 08:12:18 25 4
gpt4 key购买 nike

嘿伙计们,我一直在为我的 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 block 添加到以下代码(您发布的内容的结尾):

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未报告的异常让我困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30199449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com