gpt4 book ai didi

java - 如何在匿名线程中声明异常?

转载 作者:行者123 更新时间:2023-12-02 07:10:23 25 4
gpt4 key购买 nike

InputStream in = ClientSocket.getInputStream();
new Thread()
{
public void run() {
while (true)
{
int i = in.read();
handleInput(i);
}
}
}.start();

我正在使用这段代码在套接字上监听新数据并得到:

FaceNetChat.java:37: unreported exception java.io.IOException; must be caught or declared to be thrown
int i = in.read();
^

当我在“run()”之后添加“throws IOException”时,我得到:

FaceNetChat.java:34: run() in  cannot implement run() in java.lang.Runnable; overridden method does not throw java.io.IOException
public void run() throws IOException {
^

这可能很简单,但我不知所措。我如何通过此考试?

最佳答案

您不能覆盖 Runnable.run() 的接口(interface)这不会引发异常。您必须改为在 run 方法中处理异常。

try {
int i = in.read();
} catch (IOException e) {
// do something that makes sense for your application
}

关于java - 如何在匿名线程中声明异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6548794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com