【发布时间】:2020-08-02 20:01:30
【问题描述】:
我无法理解 Thread.sleep() 的 InterruptedException 错误被 JVM 捕获的原因,而 ThreadExecp.fun() 则并非如此。
public class ThreadExecp {
static void fun() throws InterruptedException
{
System.out.println("Inside fun(). ");
throw new InterruptedException ();
}
public static void main(String args[]) throws InterruptedException {
Thread.sleep(10000);
System.out.println("done 1");
ThreadExecp.fun();
System.out.println("Done");
}
}
在 main 方法中实际发生的错误在哪里被捕获,为什么有些可以简单地抛出而有些需要在 try-catch 中捕获?
【问题讨论】:
-
如果您的方法声明它
throws它,则可以抛出任何异常。通常,从main中抛出的那些会杀死你的程序。 -
异常通常是由于可能使您的代码处于不一致状态的结果。因此,如果程序员不通过 throw/catch 处理它们,那么最好在程序损坏您的文件之前以崩溃结束。
标签: java error-handling