user1346012
user1346012

Reputation: 11

Datagram Socket "must be caught or declared to be thrown"

The following code is producing an error

DatagramSocket socket = new DatagramSocket();

The java.net.* is included at the top

The error is unreported exception java.net.SocketException; must be caught or d eclared to be thrown

It's in a method run() in a class that uses a thread.

Any ideas?

Upvotes: 0

Views: 2342

Answers (3)

John Snow
John Snow

Reputation: 5344

Well, you are not catching the possible SocketException that might occur

try {
   DatagramSocket socket = new DatagramSocket();

    } catch (SocketException e) {
        e.printStackTrace();
    }

Upvotes: 1

Max Lybbert
Max Lybbert

Reputation: 20039

The error message is as clear as it can possibly be. Either put in a catch block:

try {
    DatagramSocket socket = new DatagramSocket();
    // ...
}
catch (SocketException ex)
{
     // ...
}

Or declare that the method you're creating the socket in can possibly throw a SocketException:

void foo() throws SocketException
{
    DatagramSocket socket = new DatagramSocket();
    // ...
}

Java has checked exceptions, meaning that the compiler watches for these things for you. I can't say it's a good part of the language, but it's a mandatory part.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533660

I suggest you catch it in a try/catch block and log it, or change your Runnable to be a Callable<Void> which can throw an excaption.

BTW: I would use an ExecutorService rather than a plain Thread as it allows you to recycle your Threads and manage them easier.

Upvotes: 2

Related Questions