0

我收到未报告的 IOException 错误尽管我构造了 try&catch 语句。

这个小程序试图调用一个 phpscript 。所以我必须在单击按钮时阅读 URL。

我是java的新手。你能解释什么是错的

错误 44:IO 异常必须被捕获或声明为抛出

URLConnection myURLConnection = myURL.openConnection();

错误 46:IO 异常必须被捕获或声明为抛出

myURLConnection.connect();

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class RegisterUser extends Applet{


 //Applet components
TextField panel1 = new TextField(10);
TextField panel2 = new TextField(10);
TextField panel3 = new TextField(10);
Button    save   = new Button("Save");



public void init(){
   //There is two text fields and a button
    add(panel1);
    add(new Label("Name:"));
    addNewLine();
    add(panel2);
    add(new Label("Last:"));
    addNewLine();
    add(save);
    addNewLine();

    // Now tell the button  what it should do when it clicked

   save.addActionListener(new SaveListener());
  }

  class SaveListener implements ActionListener{

public void actionPerformed(ActionEvent event) {

                    try
          {

          URL myURL = new URL("http://www.myplace.com/save.php?name="+panel1.getText()+"&last_name="+panel2.getText()+"&email="+panel3.getText());

          URLConnection myURLConnection = myURL.openConnection();

          myURLConnection.connect();

          }

          }
          catch (MalformedURLException e){
          System.out.println(e.getMessage());
         }
    }
      }


      private void addHorizontalLine(Color c)
   {
   // Add a Canvas 10000 pixels wide but only 1 pixel high, which acts as
   // a horizontal line to separate one group of components from the next.
   Canvas line = new Canvas( );
  line.setSize(10000,1);
  line.setBackground(c);
  add(line);
  }


  private void addNewLine( )
 {
   // Add a horizontal line in the background color. The line itself is
   // invisible, but it serves to force the next Component onto a new line.
   addHorizontalLine(getBackground( ));
}

}

4

2 回答 2

2

IOException你必须像这样抓住检查

catch (IOException exc) {
  // handle exception
}

在你的try catch你只能抓住MalformedURLException这就是你得到编译错误的原因。

于 2012-10-23T11:07:48.937 回答
1

看起来你在-block}之后有太多了。try

你还必须赶上IOException

像这样写:

      try{
        URL myURL = new URL("http://www.myplace.com/save.php?name="+panel1.getText()+"&last_name="+panel2.getText()+"&email="+panel3.getText());
        URLConnection myURLConnection = myURL.openConnection();
        myURLConnection.connect();
      }catch (MalformedURLException e){
        System.out.println(e.getMessage());
      }catch (IOException e2){
        System.out.println(e2.getMessage());
      }
于 2012-10-23T11:19:44.600 回答