I’ve the next code, based on an example to use Java UDPSocket() (not built-in a class):
package BomberButti;
import java.io.*;
import java.net.*;
/**
* BomberServer
* Hier wordt de Server opgezet waarop Clients kunnen connecteren om vervolgens tegen elkaar te spelen
* @author Kaj
*/
public class BomberServer {
public BomberServer() {
waitForPlayers();
}
public static void waitForPlayers() throws Exception {
try {
DatagramSocket serverSocket = new DatagramSocket(9876); //Socket openen
byte[] receiveData = new byte[1024]; //Ontvangen gegevens
byte[] sendData = new byte[1024]; //Te verzenden gegevens
while(true) {
receiveData = new byte[1024];
//Ontvangen data (als die er is) ophalen
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
System.out.println ("Waiting for datagram packet");
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
System.out.println ("From: " + IPAddress + ":" + port);
System.out.println ("Message: " + sentence);
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
sendData = new String("Request accepted").getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);
serverSocket.send(sendPacket);
}
}
catch(SocketException ex) {
System.out.println("UDP Port 9876 is occupied.");
System.exit(1);
}
}
public static void main(String args[]) {
BomberServer server = new BomberServer();
}
}
When trying to run this code I get the error ‘unreported exception Exception; must be caught er declared to be thrown’.
I understand that this has to do with the ‘throws Exception’ I placed behind the declaration of my waitForPlayers() method. But when I remove this throws Exception part, I get an error at the line: serverSocket.receive(receivePacket); ‘unreporter exception IOException; must be declared to be thrown’ so I guess none of the both ways I tried is the right way.
So how do I have to do it that it’s correct?
Sincerely,
Luxo
The code inside
waitForPlayers()can throw an IOException, so the method should declare that it throws an IOException (and not an Exception, because Exception is too vague):Since this method can throw an IOException, and you call this method from the constructor without catching IOException, the constructor must also declare that it throws IOException:
And of course, the method which calls this constructor will also have to either catch IOException, or declare that it throws IOException, etc. etc. until you get to a point where you can handle this IOException, and thus catch it to handle it.
Read the tutorial about exceptions.
Important note: catching an exception, printing its stack trace, and continuing as if nothing happened is generally not how an exception should be handled.