如何在调用Thread.sleep()时修复未处理异常的编译错误?

Mr.*_*led 23 java exception-handling checked-exceptions

我是Java的新手,也是编程的新手(我知道直接进入Java可能不是最好的主意.)而且无论我如何尝试在程序中添加暂停,我都会遇到错误.我正在做一个简单的计数程序,并希望在每个数字之间添加一秒延迟,这是我到目前为止的代码:

import java.lang.*;

public class Counter
{
    public static void main(String[]args)
    {
        int i;

        for (i = 0; i <= 10; i++)
        {
            Thread.sleep(1000);
            System.out.println(i);
        }
        System.out.println("You can count to ten.");
    }
}
Run Code Online (Sandbox Code Playgroud)

调用Thread.sleep()不会编译.该javac编译器说:"没有报告异常InterruptedException异常;必须捕获或声明抛出"和Eclipse说,"未处理的异常类型InterruptedException的"

Mar*_*ers 56

Thread.sleep可以抛出InterruptedException,这是一个经过检查的异常.必须捕获并处理所有已检查的异常,否则您必须声明您的方法可以抛出异常.无论是否实际抛出异常,都需要这样做.不声明您的方法可以抛出的已检查异常是编译错误.

你需要抓住它:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
    // handle the exception...        
    // For example consider calling Thread.currentThread().interrupt(); here.
}
Run Code Online (Sandbox Code Playgroud)

或者声明你的方法可以抛出InterruptedException:

public static void main(String[]args) throws InterruptedException
Run Code Online (Sandbox Code Playgroud)

有关