简体   繁体   English

在扩展类上添加“抛出”?

[英]Adding 'throws' on an extended class?

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. 我使用Socket API开发了一个简单的应用程序,但是遇到了一个小问题,但找不到答案。

The application is supposed to be multi-threaded, so that the main method starts both the server and client threads. 该应用程序应该是多线程的,因此main方法可以启动服务器和客户端线程。

public class UDPClientServer1 extends Thread

However, since the the Socket classes need to throw some specific exceptions, I must also do this: 但是,由于Socket类需要引发一些特定的异常,因此我还必须这样做:

public void runClient() throws SocketException, UnknownHostException, IOException

and similarly for the runServer() method. 同样适用于runServer()方法。

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. 理想情况下,您可能希望包装抛出的异常,如果错误无法恢复,则将其转换为RuntimeException ,或者至少是一个更适当的/封装的异常。

Eg 例如

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. 上面的ClientException是您自己需要创建的异常。 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. 但是,如果没有合理的方式让调用代码响应异常,则使用RuntimeException可能更合适。 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). 引发RuntimeException时,不必在方法签名中声明它,并且调用代码不需要显式处理它(尽管应在某个时候处理它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM