如何修复调用 Thread.sleep() 时未处理异常的编译错误? [英] How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

查看:93
本文介绍了如何修复调用 Thread.sleep() 时未处理异常的编译错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Java 新手,而且对编程有点陌生(我知道直接进入 Java 可能不是最好的主意.)无论我如何尝试在我的程序.我正在做一个简单的计数程序,想在每个数字之间添加一秒的延迟,这是我目前拥有的代码:

I am new to Java and kind of new to programming (I know diving straight into Java probably wasn't the greatest idea.) and I've been getting an error consistently no matter how I try to add a pause in my program. I am doing a simple counting program and want to add a one second delay between each number here is the code I have so far:

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.");
    }
}

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

The call to Thread.sleep() won't compile. The javac compiler says, "unreported exception InterruptedException; must be caught or declared to be thrown" and Eclipse says, "Unhandled exception type InterruptedException"

推荐答案

Thread.sleep 可以抛出一个已检查异常的 InterruptedException.所有检查的异常都必须被捕获和处理,否则您必须声明您的方法可以抛出它.无论是否实际抛出异常,您都需要执行此操作.未声明您的方法可以抛出的已检查异常是编译错误.

Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.

你要么需要抓住它:

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

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

Or declare that your method can throw an InterruptedException:

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

相关

这篇关于如何修复调用 Thread.sleep() 时未处理异常的编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆