如何从java线程中抛出一个检查过的异常? [英] How to throw a checked exception from a java thread?

查看:220
本文介绍了如何从java线程中抛出一个检查过的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我正在编写一个网络应用程序,在其中我读取了一些自定义二进制格式的数据包。我正在启动一个后台线程来等待传入的数据。问题是,编译器不允许我将任何代码抛出(已检查)异常放入 run()。它说:

Hey, I'm writing a network application, in which I read packets of some custom binary format. And I'm starting a background thread to wait for incoming data. The problem is, that the compiler doesn't let me to put any code throwing (checked) exceptions into run(). It says:

run() in (...).Listener cannot implement run() in java.lang.Runnable; overridden method does not throw java.io.IOException

我希望异常终止该线程,并让它在父线程的某处被捕获。这是可能实现还是我必须处理里面的线程?

I want the exception to kill the thread, and let it be caught somewhere in the parent thread. Is this possible to achieve or do I have to handle every exception inside the thread?

推荐答案

警告:如果必须使用异常机制,这可能无法满足您的需求。

Caveat: this may not meet your needs if you have to use the exception mechanism.

如果我理解正确,您实际上不需要检查异常(您已经接受了建议未经检查的异常的答案)那么一个简单的监听器模式会更合适吗?

If I understand you correctly, you don't actually need the exception to be checked (you've accepted the answer suggesting an unchecked exception) so would a simple listener pattern be more appropriate?

监听器可以存在于父线程中,当你捕获时在子线程中检查了异常,你可以简单地通知监听器。

The listener could live in the parent thread, and when you've caught the checked exception in the child thread, you could simply notify the listener.

这意味着你有办法暴露这种情况(通过公共方法),以及将能够传递比异常允许的更多信息。但它确实意味着父线程和子线程之间将存在耦合(尽管是松散的)。这取决于你的具体情况,这是否比使用未经检查的异常包装已检查的异常有好处。

This means that you have a way of exposing that this will happen (through public methods), and will be able to pass more information than an exception will allow. But it does mean there will be a coupling (albeit a loose one) between the parent and the child thread. It would depend in your specific situation whether this would have a benefit over wrapping the checked exception with an unchecked one.

这是一个简单的例子(从另一个答案中借用了一些代码) :

Here's a simple example (some code borrowed from another answer):

public class ThingRunnable implements Runnable {
    private SomeListenerType listener;
    // assign listener somewhere

    public void run() {
        try {
            while(iHaveMorePackets()) { 
                doStuffWithPacket();
            }
        } catch(Exception e) {
            listener.notifyThatDarnedExceptionHappened(...);
        }
    }
 }

耦合来自一个对象在父线程中必须是 SomeListenerType

The coupling comes from an object in the parent thread having to be of type SomeListenerType.

这篇关于如何从java线程中抛出一个检查过的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆