2016-08-09 66 views
-1

此代碼中發生了哪種類型的異常。
爲什麼catch語句不採取ArrayOutofBoundsException eArrayOutofBoundsException e

import java.io.*; 
import java.util.*; 
import java.text.*; 
import java.math.*; 
import java.util.regex.*; 

public class Solution { 

public static void main(String[] args) { 
    int i,j,k,n,m,l,x,y; 

    Scanner sc=new Scanner (System.in); 
    n=sc.nextInt(); 
    ArrayList [] a=new ArrayList[n]; 
    for(i=0;i<n;i++) 
     { 
     m=sc.nextInt(); 
     a[i]=new ArrayList(); 
     for(j=0;j<m;j++) 
     { 
      a[i].add(sc.nextInt()); 
     } 
    } 
    k=sc.nextInt(); 
    for(i=0;i<k;i++) 
     { 
     x=sc.nextInt(); 
     y=sc.nextInt(); 
     try 
      { 
      System.out.println(a[x-1].get(y-1)); 
     } 
     catch(ArrayOutofBoundsException e) 
      { 
      System.out.println("ERROR!"); 
     } 
    } 

    } 
} 
+0

哪條線是個例外? – mcalex

+0

檢查它是否正確...它捕捉異常。 – Subhankar

回答

2

由於您使用的ArrayList數組中的程序,

從Java文檔的ArrayList的獲得方法

拋出: IndexOutOfBoundsException - 如果索引超出範圍(index < 0 || index> = size())

and

在運行時檢查所有數組訪問;嘗試使用小於零或大於或等於 數組長度的索引 會導致拋出ArrayIndexOutOfBoundsException。

所以你試着在你的程序中搭配IndexOutOfBoundsException以及ArrayIndexOutOfBoundsException

例:

try { 
    System.out.println(a[x - 1].get(y - 1)); 
} catch (ArrayIndexOutOfBoundsException e) { 
    System.out.println("ERROR!"); 
} catch (IndexOutOfBoundsException e) { 
    System.out.println("ERROR! IndexOutOfBoundsException "); 
} 
+0

感謝您的建議 –

相關問題