在Java的try、catch和finally塊之間可以編寫任何語句嗎?


不,我們不能在**try、catch和finally塊**之間編寫任何語句,這些塊**構成一個單元**。**try**關鍵字的功能是識別異常物件,捕獲該異常物件,並透過暫停**try塊**的執行,將控制權連同識別的異常物件一起轉移到**catch塊**。**catch塊**的功能是接收**try**傳送的異常類物件,並捕獲該異常類物件,並將該異常類物件賦值給在**catch塊**中定義的相應異常類的引用。**finally塊**是無論是否發生異常都一定會執行的塊。

我們可以編寫諸如**try帶catch塊**、**try帶多個catch塊**、**try帶finally塊**和**try帶catch和finally塊**之類的語句,而不能在這些組合之間編寫任何程式碼或語句。如果嘗試在這些塊之間放置任何語句,則會丟擲**編譯時錯誤**。

語法

try
{
   // Statements to be monitored for exceptions
}
// We can't keep any statements here
catch(Exception ex){
   // Catching the exceptions here
}
// We can't keep any statements here
finally{
   // finally block is optional and can only exist if try or try-catch block is there.
   // This block is always executed whether exception is occurred in the try block or not
   // and occurred exception is caught in the catch block or not.
   // finally block is not executed only for System.exit() and if any Error occurred.
}

示例

線上演示

public class ExceptionHandlingTest {
   public static void main(String[] args) {
      System.out.println("We can keep any number of statements here");
      try {
         int i = 10/0; // This statement throws ArithmeticException
         System.out.println("This statement will not be executed");
      }
      //We can't keep statements here
      catch(ArithmeticException ex){
         System.out.println("This block is executed immediately after an exception is thrown");
      }
      //We can't keep statements here
      finally {
         System.out.println("This block is always executed");
      }
         System.out.println("We can keep any number of statements here");
   }
}

輸出

We can keep any number of statements here
This block is executed immediately after an exception is thrown
This block is always executed
We can keep any number of statements here

更新於:2020年2月6日

3K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

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