【发布时间】:2020-07-08 17:23:47
【问题描述】:
如果在此处的 try 块中抛出异常,finally 块将执行:
public class ExceptionTest{
public static void main(String args[])
{
System.out.println(print());
}
public static int print()
{
try
{
throw new NullPointerException();
}
finally
{
System.out.println("Executing finally block");
}
}
}
输出:
Executing finally block
Exception in thread "main" java.lang.NullPointerException
at ExceptionTest.print(ExceptionTest.java:11)
at ExceptionTest.main(ExceptionTest.java:4)
另一方面 finally 不会在此代码中被调用:
public class ExceptionTest{
public static void main(String args[])
{
System.out.println(print());
}
public static int print()
{
try
{
throw new Exception();
}
finally
{
System.out.println("Executing finally block");
}
}
}
输出:
ExceptionTest.java:11: error: unreported exception Exception; must be caught or declared to be thrown
throw new Exception();
^
1 error
为什么 NullPointerException 类很酷,但在涉及 Exception 类时却报错?
【问题讨论】:
-
NullPointerException是一个未经检查的异常。 -
如果整个程序不运行,finally块就不会运行
-
@luk2302 当我开始研究 finally 块时,我读到“finally 块总是在 try 块退出时执行。所以你可以在没有 catch 的情况下使用 finally,但你必须使用 try。” *.com/questions/17314724/… 认为这是各种异常的可能。
-
您的代码根本无法运行,甚至无法编译。关于
finally的陈述仍然正确,但根本不适用于您的情况,因为首先没有任何东西在运行。 -
@luk2302 谢谢你,我现在明白了。
标签: java exception finally try-finally