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

查看:28
本文介绍了java - 如何从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 - 如何从java线程抛出检查异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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