首页 > 解决方案 > 如果抛出异常,finally 块不会执行

问题描述

如果在 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 类时却抱怨?

标签: javaexceptionfinallytry-finally

解决方案


NullPointerException 是未经检查的异常。检查本指南

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

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

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

推荐阅读