【问题标题】:finally block does not execute if exception is thrown [duplicate]如果抛出异常,finally块不会执行[重复]
【发布时间】: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


【解决方案1】:

NullPointerException 是未经检查的异常。检查这个guide

这是一个捕获所有内容的 try and catch 块的示例:

try {
    //Do Something
    }
 
catch (Exception e) {
      System.out.println("Something went wrong.");
    } 

finally {
      System.out.println("The 'try catch' is finished.");
    }

【讨论】:

  • 它没有捕捉到一切,它没有捕捉到Errors 或其他Throwables。