时的未处理异常的编译错误

时的未处理异常的编译错误

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

问题描述

我刚刚开始使用Java和新的编程(我知道直接进入Java可能不是最好的想法),而且我一直在错误地得到错误,无论我如何尝试在我的程序。我正在做一个简单的计数程序,并希望在每个号码之间添加一秒钟的延迟是我迄今为止的代码:

  import java.lang。*; 

public class Counter
{
public static void main(String [] args)
{
int i; (i = 0; i< = 10; i ++)


{
Thread.sleep(1000);
System.out.println(i);
}
System.out.println(你可以算到十。);
}
}

调用线程。 sleep()不会编译。 codejavac 编译器说:未报告异常InterruptedException;必须被捕获或声明被抛出,Eclipse说:未处理的异常类型InterruptedException

解决方案

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



你需要抓住它:

  try {
Thread.sleep(1000);
} catch(InterruptedException e){
e.printStackTrace();
//处理异常...
//例如考虑调用Thread.currentThread()。这里。
}

或声明您的方法可以抛出一个 InterruptedException

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

相关








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

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 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.

You either need to catch it:

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

Or declare that your method can throw an InterruptedException:

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

Related

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

08-19 09:53