範例:例外處理

[Java]例外處理 exception handing(基本概念)中提到「例外類別」,指的是 拋出的物件所屬類別。

Array Index Out Of Bounds Exception 就是例外類別的一種

我們將以上的範例做修改,加入try catch finally 的敘述:

public static void main(String args[])
{
   try
   {
      int arr[]=new int[5];
      arr[10]=7;
   }
   catch(ArrayIndexOutOfBoundsException e)
   {
      System.out.println("索引值超出範圍");
   }
   finally        // 此區塊那敘述一定會被執行
   {
   System.out.println("finally 中敘述");
   }
   System.out.println("try-catch-finally 敘述之外");
}

讓我們再看一次流程圖:

因此 try 中敘述將檢查是否有例外發生

try
{
   int arr[]=new int[5];
   arr[10]=7;
}

如果有例外發生,而且這個例外又是ArrayIndexOutOfBoundsException 類別, 就會印出 索引值超出範圍

catch(ArrayIndexOutOfBoundsException e)
{
      System.out.println("索引值超出範圍");
}

最後不管以上例外是否發生與捕捉,finally 中敘述都會被執行, 因此會印出 finally 中敘述

finally        // 此區塊那敘述一定會被執行
{
   System.out.println("finally 中敘述");
}

透過例外的機制,除了能夠讓程式執行到最後,而且還能加上錯誤訊息的提示。

那麼, 在例外類別後方又加上一個 e 是什麼意思呢?

catch(ArrayIndexOutOfBoundsException e)

e 是一個可以自己命名的變數名稱,也就是說 這是用例外類別建立的類別變數。 我們可以透過這個變數來顯示例外的相關訊息:

catch(ArrayIndexOutOfBoundsException e)
{
   System.out.println("索引值超出範圍");
   System.out.println("訊息:"+e);
}

如此一來,如果有例外發生,而且這個例外又是ArrayIndexOutOfBoundsException 類別, 就會印出 索引值超出範圍 且能夠印出 訊息:Array Index Out Of Bounds Exception : 10

Last updated