首頁  >  文章  >  Java  >  在Java中,我們可以使用try塊而不帶catch塊嗎?

在Java中,我們可以使用try塊而不帶catch塊嗎?

王林
王林轉載
2023-08-19 13:29:131462瀏覽

在Java中,我們可以使用try塊而不帶catch塊嗎?

是的,可以使用final區塊在沒有catch區塊的情況下嘗試執行。

我們知道,final區塊將始終執行,即使在try區塊中發生了異常,除非使用System.exit(),它將始終執行。

範例1

public class TryBlockWithoutCatch {
   public static void main(String[] args) {
      try {
         System.out.println("Try Block");
      } finally {
         System.out.println("Finally Block");
      }
   }
}

輸出

Try Block
Finally Block

即使方法有回傳類型且try區塊傳回某個值,最終區塊仍會執行。

範例2

public class TryWithFinally {
   public static int method() {
      try {
         System.out.println("Try Block with return type");
         return 10;
      } finally {
         System.out.println("Finally Block always execute");
      }
   }
   public static void main(String[] args) {
      System.out.println(method());
   }
}

輸出

Try Block with return type
Finally Block always execute
10

以上是在Java中,我們可以使用try塊而不帶catch塊嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除