Kaj
Kaj

Reputation: 2503

Java class using exceptions

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

Upvotes: 0

Views: 197

Answers (3)

tcb
tcb

Reputation: 2814

Add throws Exception to BomberServer() and main():

public class BomberServer {

    public BomberServer() throws Exception {
        waitForPlayers();
    }

    public static void waitForPlayers() throws Exception {
        ...
    }
    public static void main(String args[]) throws Exception {
        BomberServer server = new BomberServer();
    }
}

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691735

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):

public static void waitForPlayers() throws IOException {

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:

public BomberServer() 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.

Upvotes: 3

Mel Nicholson
Mel Nicholson

Reputation: 3225

The error message could be a little clearer. The declaration in waitForPlayers() is mostly fine, but you need to make a similar declaration in the code that calls it (and the code that calls that...) until you get all the way to main( ) or a try...catch block.

Being more specific and saying IOException instead of just Exception might be a little safer.

Upvotes: 0

Related Questions