【问题标题】:"Unreported exception" from method call despite catching esception尽管捕获异常,但来自方法调用的“未报告的异常”
【发布时间】:2017-11-17 14:08:36
【问题描述】:

我在以下代码部分收到 3 个错误:

public static void main(String[] args){

     CS_Socket cs = new CS_Socket();

     try{
         new Thread(() -> cs.EchoServer()).start();
         new Thread(() -> cs.EchoClient()).start();
       }

     catch(IOException e){

       System.out.println(e.getMessage());

     }
}

对于这两个新线程,我收到 unreported exception java.io.IOException; must be caught or declared to be thrown 作为编译器错误。

catch(IOException e),我收到exception java.io.IOException is never thrown in body of corresponding try statement

我是 Java 新手,不知道如何修复这些错误。关于这些错误的其他问题似乎都没有包含与我的代码相关的答案。

非常感谢任何帮助。

【问题讨论】:

  • try{ 放在CS_Socket 行之前,可能是这一行可能会抛出IOException
  • @Berger 不,我仍然得到错误。
  • 看起来像 CS_Socket.EchoServer()CS_Socket.EchoClient() 是需要 catch() 语句的方法。如果您可以发布课程 CS_Socket 的代码会有所帮助

标签: java exception exception-handling try-catch java-io


【解决方案1】:

在一个线程中抛出的异常通常无法在另一个线程中捕获。

更多解释见此链接How to catch an Exception from a thread

【讨论】:

  • 请查看修改后的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-18
  • 2012-02-01
  • 2016-05-10
  • 2016-12-17
  • 1970-01-01
  • 2015-04-22
  • 2022-01-13
相关资源
最近更新 更多