Java 中的 catch 或 finally 塊中可以有 return 語句嗎?


是的,可以在 catch 和 finally 塊中編寫方法的 return 語句。

  • 存在這樣的情況:方法具有返回型別,並且我們可以根據條件在方法的任何部分返回某個值。

  • 如果我們在 catch 塊中返回一個值,並且可以在方法末尾返回一個值,則程式碼將成功執行。

  • 如果我們在 catch 塊中返回一個值,並且可以在返回一個值後在方法末尾編寫一條語句,則程式碼將不會執行,因此它變成了不可達程式碼,因為我們知道 Java 不支援不可達程式碼。

  • 如果我們在 final 塊中返回一個值,則不需要在方法末尾保留返回值。

示例 1

public class CatchReturn {
   int calc() {
      try {
         int x=12/0;
      } catch (Exception e) {
         return 1;
      }
      return 10;
   }
   public static void main(String[] args) {
      CatchReturn cr = new CatchReturn();
      System.out.println(cr.calc());
   }
} 

輸出

1

示例 2

public class FinallyReturn {
   int calc() {
      try {
         return 10;
      } catch(Exception e) {
         return 20;
      } finally {
         return 30;
      }
   }
   public static void main(String[] args) {
      FinallyReturn fr = new FinallyReturn();
      System.out.println(fr.calc());
   }
} 

輸出

30 

更新日期: 17-11-2023

13K+ 瀏覽量

啟動您的職業生涯

透過完成課程取得認證

開始學習
廣告
© . All rights reserved.