我目前正在连接到IRC服务器,并且收到一条错误消息,提示“错误:(20,16)java:未报告的异常java.io.IOException;必须捕获或声明为抛出“
public connection(String host, int port){
this.host = host;
this.port = port;
connect(); //This line is erroring
register();
}
private PrintStream out;
private void connect() throws IOException, UnknownHostException {
Socket socket = new Socket(host, port);
out = new PrintStream(socket.getOutputStream());
}
我也尝试过
private PrintStream out;
private void connect() throws IOException, UnknownHostException {
try {
Socket socket = new Socket(host, port);
out = new PrintStream(socket.getOutputStream());
} catch (UnknownHostException ex){
System.out.println(ex.getMessage());
}
}
以及
private PrintStream out;
private void connect() throws IOException, UnknownHostException {
try {
Socket socket = new Socket(host, port);
try {
out = new PrintStream(socket.getOutputStream());
} catch(IOException exc){
System.out.println(exc.getMessage());
}
} catch (UnknownHostException ex){
System.out.println(ex.getMessage());
}
}
但是该错误在我尝试过的所有选项中仍然存在。
答案 0 :(得分:1)
您已经定义了引发IOException和UnknownHostException的方法。
private void connect() throws IOException, UnknownHostException {
}
现在,当您调用此方法时,必须像波纹管一样处理这些异常。
try {
connect();
} catch (IOException e) {
e.printStackTrace();
}
另一方面,您在connect()方法中发现了错误。因此,没有真正的要求将它们再次放入方法定义中。例如,您可以定义如下的方法。如果您使用此路由,则可以使用当前语法调用connect()方法。
private void connect(){
}
答案 1 :(得分:0)
您必须用try catch包围connect()。 connect方法引发异常。
public connection(String host, int port){
this.host = host;
this.port = port;
try{
connect(); //This line is erroring
}catch(Exception e){}
register();
}