为什么我需要处理Thread.sleep()的异常? [英] Why do I need to handle an exception for Thread.sleep()?

查看:169
本文介绍了为什么我需要处理Thread.sleep()的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要编译此代码,我可以:

To get this code to compile, I can either:

  • Put my call to Thread.sleep() in a try/catch block, or
  • Have printAll() declare that it can throw an InterruptedException.

为什么我必须这样做?

class Test {
    public static void main( String[] args ) {
          printAll( args );
    }

    public static void printAll( String[] line ) {
        System.out.println( lines[ i ] );
        Thread.currentThread().sleep( 1000 ):
    }
}

Kathy Sierra的SCJP书籍中的示例代码。)

我知道 Thread.sleep()抛出的异常是一个经过检查的异常,所以我必须处理它,但在什么情况下 Thread.sleep()需要抛出此异常吗?

I know that the exception which Thread.sleep() throws is a checked exception, so I have to handle it, but in what situation does Thread.sleep() need to throw this exception?

推荐答案

如果方法是以某种方式声明它可以抛出已检查的异常( Exception s,它们不是 RuntimeException 的子类),代码调用它必须在 try-catch 块中调用它,否则调用者方法必须声明抛出它。

If a method is declared in a way that it can throw checked exceptions (Exceptions that are not subclasses of RuntimeException), the code that calls it must call it in a try-catch block or the caller method must declare to throw it.

< a href =http://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#sleep-long-> Thread.sleep() 声明如下:

Thread.sleep() is declared like this:

public static void sleep(long millis) throws InterruptedException;

它可能抛出 InterruptedException 直接扩展 java.lang.Exception 所以你必须抓住它或声明抛出它。

It may throw InterruptedException which directly extends java.lang.Exception so you have to catch it or declare to throw it.

为什么 Thread.sleep()以这种方式声明?因为如果 Thread 正在休眠,线程可能会被中断,例如使用 Thread.interrupt() ,在这种情况下,休眠线程( sleep()方法)将抛出此的实例InterruptedException

And why is Thread.sleep() declared this way? Because if a Thread is sleeping, the thread may be interrupted e.g. with Thread.interrupt() by another thread in which case the sleeping thread (the sleep() method) will throw an instance of this InterruptedException.

示例:

Thread t = new Thread() {
    @Override
    public void run() {
        try {
            System.out.println("Sleeping...");
            Thread.sleep(10000);
            System.out.println("Done sleeping, no interrupt.");
        } catch (InterruptedException e) {
            System.out.println("I was interrupted!");
            e.printStackTrace();
        }
    }
};
t.start();     // Start another thread: t
t.interrupt(); // Main thread interrupts t, so the Thread.sleep() call
               // inside t's run() method will throw an InterruptedException!

输出:

Sleeping...
I was interrupted!
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at Main$1.run(Main.java:13)

这篇关于为什么我需要处理Thread.sleep()的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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