【问题标题】:Error even after throws Exception for thread.sleep即使在为 thread.sleep 抛出异常之后也会出错
【发布时间】:2020-03-04 09:16:19
【问题描述】:

我正在尝试让我的线程睡眠并让方法抛出 InterruptedException,但它仍然给出错误“未处理的异常”


  @Before
    public void setUp() throws InterruptedException{

        simulatorList.forEach(simulation -> {
           ....
            Thread.sleep(1000*60*1);
//giving error here 

            ...
        });
}

【问题讨论】:

  • 你的问题不清楚。这里的期望是什么?

标签: java


【解决方案1】:

因为你在foreach里面调用了Thread.sleep,下面会解决你的问题:

public void setUp() throws InterruptedException {
    List<String> simulatorList = new ArrayList<>();
    for (String s : simulatorList) {
        Thread.sleep(1000 * 60 * 1);
    }
}

【讨论】:

    【解决方案2】:

    原因可以从 lambda 抛出异常。处理它的最简单方法是重新抛出 RuntimeException。喜欢

    public void setUp(){
    
        new LinkedList<String>().forEach(simulation -> {
            try {
                Thread.sleep(1000*60*1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
    }
    

    如果您真的期望 InterruptedException,您可以创建自己的扩展 RuntimeException 的异常,例如 RuntimeInterruptedException,重新抛出它,然后在您的流程中处理。

    【讨论】:

      猜你喜欢
      • 2015-07-10
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 2021-06-19
      • 1970-01-01
      • 2020-07-20
      • 2022-06-15
      • 2019-11-11
      相关资源
      最近更新 更多