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

查看:40
本文介绍了如何在调用 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天全站免登陆