I'm making a simple application with the Socket API, but have run into a small issue that I haven't found the answer for.

The application is supposed to be multi-threaded, so that the main method starts both the server and client threads.

public class UDPClientServer1 extends Thread

However, since the the Socket classes need to throw some specific exceptions, I must also do this:

public void runClient() throws SocketException, UnknownHostException, IOException

and similarly for the runServer() method.

Not that there's anything wrong with that, but is there a more elegant solution? Something along the lines of :

public class UDPClientServer1 extends Thread, throws Exception
有帮助吗?

解决方案

Ideally you may want to wrap the exception that your throw, either converting it to a RuntimeException if the error is unrecoverable, or at least a more appropriate / encapsulated exception.

E.g.

public void runClient throws ClientException
{
    try
    {
        // do something
    } catch (Exception e)
    {
        log.error("Exception encountered in client",e);
        throw new ClientException("Unrecoverable client exception encountered",e);
        // or: throw new RuntimeException("Unrecoverable client exception",e);
    }
}

ClientException in the above is your own exception that you would need to create. Its purpose is to encapsulate the implementation details of corresponding exceptions from any calling code.

Using a RuntimeException, however, may be more appropriate if there is no reasonable way for the calling code to respond to the exception. When throwing a RuntimeException you do not have to declare it in the method signature and calling code does not need to explicitly handle it (although it should be handled at some point).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top