Reputation: 21
I'm working on connecting to an IRC server currently, and I'm getting an error thrown saying "Error:(20, 16) java: unreported exception java.io.IOException; must be caught or declared to be thrown"
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());
}
I have also tried
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());
}
}
As well as
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());
}
}
But the error persists through all options that I have tried.
Upvotes: 1
Views: 626
Reputation: 422
You have defined your method to throw IOException and UnknownHostException.
private void connect() throws IOException, UnknownHostException {
}
Now when you call this method you have to handle these Exceptions like bellow.
try {
connect();
} catch (IOException e) {
e.printStackTrace();
}
On the other hand, you have caught the errors inside the connect() method. So there is no real requirement to throw them again in the method definition. For example, you can define your method like below. If you go with this route you can call connect() method with your current syntax.
private void connect(){
}
Upvotes: 1
Reputation: 321
You must surround connect() with a try catch. The connect method throws the exception.
public connection(String host, int port){
this.host = host;
this.port = port;
try{
connect(); //This line is erroring
}catch(Exception e){}
register();
}
Upvotes: 0