嘿伙计们我一直在为我的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")));
}
}
答案 0 :(得分:1)
只需将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();
}
}}
答案 1 :(得分:0)
通常,任何IO操作都可能导致异常。根据您的需要,最简单的解决方案就是将throws IOException
放在您看到问题的方法的顶部,但这不是很好的做法,在这种情况下不起作用。在问题行周围放置一个try / catch块,并包含有意义的错误消息,这可能是最好的方法。