iT邦幫忙

DAY 26
0

Java重點學習筆記系列 第 26

Java重點筆記 23:Try/Catch的Finally

Try/catch句法還有一個關鍵字:Finally。Finally段的程式碼是不管有沒有捉到Exceptions都會執行。

句法結構:

try
{
   //Protected code
}catch(ExceptionType1 e1)
{
   //Catch block
}catch(ExceptionType2 e2)
{
   //Catch block
}catch(ExceptionType3 e3)
{
   //Catch block
}finally
{
   //The finally block always executes.
}

以下是例子:

public class ExcepTest{

   public static void main(String args[]){
      int a[] = new int[2];
      try{
         System.out.println("Access element three :" + a[3]);
      }catch(ArrayIndexOutOfBoundsException e){
         System.out.println("Exception thrown  :" + e);
      }
      finally{
         a[0] = 6;
         System.out.println("First element value: " +a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}

結果顯示如下:

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

[image credit: JAY MANTRI]


上一篇
Java重點筆記 22:捕捉多種Exceptions
下一篇
Java重點筆記 24:Java物件導向之繼承(Inheritance)
系列文
Java重點學習筆記30

尚未有邦友留言

立即登入留言