gpt4 book ai didi

java - 未处理的异常?

转载 作者:行者123 更新时间:2023-12-01 11:58:05 25 4
gpt4 key购买 nike

我花了几个小时试图解决这个问题;我是 Java 新手,我似乎无法找出为什么 java Thread 函数抛出异常错误。谁能给我解释一下吗?

import java.util.Calendar;
import java.util.Date;

public class Loops {

public static void main(String [] args) {



Date today = new Date();
System.out.println(today);

Calendar cal = Calendar.getInstance();
cal.set(2015, 1, 1, 0, 3, 0);

while (today.before(cal.getTime()))
{
System.out.println("Waiting");
Thread.sleep(1000);
today = new Date();
System.out.println(today);
}

System.out.println("Done");


}

}

最佳答案

查看Thread.java API,方法sleep();抛出异常。

public static native void sleep(long millis) throws InterruptedException;

因此需要捕获异常重新抛出异常

抛出异常

public static void main(String[] args) throws InterruptedException {

Date today = new Date();
System.out.println(today);

Calendar cal = Calendar.getInstance();
cal.set(2015, 1, 2, 0, 3, 0);

while (today.before(cal.getTime())) {
System.out.println("Waiting");
Thread.sleep(1000);
today = new Date();
System.out.println(today);
}

System.out.println("Done");

}

捕获异常

 public static void main(String[] args) {

Date today = new Date();
System.out.println(today);

Calendar cal = Calendar.getInstance();
cal.set(2015, 1, 2, 0, 3, 0);

while (today.before(cal.getTime())) {
System.out.println("Waiting");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
today = new Date();
System.out.println(today);
}

System.out.println("Done");

}

关于java - 未处理的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28271514/

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