有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我必须包装每一条线。try/catch语句中的sleep()调用?

我正在尝试用Java编写我的第一个多线程程序。我不明白为什么我们需要围绕for循环进行这种异常处理。当我在没有try/catch子句的情况下编译时,它会给出一个InterruptedException

以下是信息:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Unhandled exception type InterruptedException

但是当使用try/catch运行时,catch块中的sysout永远不会显示——这意味着无论如何都没有捕获到这样的异常

public class SecondThread implements Runnable {
    Thread t;
    
    SecondThread() {
        t = new Thread(this, "Thread 2");
        t.start();
    }

    public void run() {
        try {
            for (int i=5; i>0; i--) {
                System.out.println("thread 2: " + i);
                Thread.sleep(1000);
            }
        }
        catch (InterruptedException e) {
            System.out.println("thread 2 interrupted");
        }
    }
}

public class MainThread {

    public static void main(String[] args) {
        new SecondThread();
    
        try {
            for (int i=5; i>0; i--) {
                System.out.println("main thread: " + i);
                Thread.sleep(2000);
            }
        }
        catch (InterruptedException e) {
            System.out.println("main thread interrupted");
        }
    }
}

共 (2) 个答案

  1. # 1 楼答案

    When I compile without the try/catch clauses it gives an InterruptedException.

    异常是在运行时抛出的,而不是在编译时抛出的,所以这不可能是真的

    可能您得到的编译错误是Thread.sleep可以抛出InterruptedException,但是调用Thread.sleepSecondThread.run没有声明它可以抛出它。因此,编译器会失败,因为异常无法转移到任何地方

    通常有两种解决方法:

    • 捕捉异常,或者
    • 在方法中添加throws子句

    在这种情况下,后者是不可能的,因为SecondThread.run重写了Runnable.run,而Runnable.run并不声明它引发任何异常。所以你需要捕捉异常

    如果情况并非如此,或者您的意思是“在编译后运行时,如果没有try/catch子句,则会产生InterruptedException”,请附上您收到的确切错误信息。事实上,你在这里提问时应该这样做

  2. # 2 楼答案

    InterruptedException是一个已检查的异常,必须捕获。在代码中,它是通过sleep方法抛出的。因此,如果不将其包装或重新引用,编译器将停止,因为这是一个已检查的异常

    但在您的示例程序中,它在正常情况下永远不会被抛出,因为您不会中断。然而,它是为了确保当一个正在睡眠、等待或处于“僵尸”状态的线程设置了中断标志,从而被代码或操作系统级调用中断时,有处理代码

    因此,事实上,它是捕获所必需的,并且有着有效的用途