ArrayIndexOutOfBoundsException的用户定义异常

时间:2016-06-07 16:13:14

标签: java arrays exception

如果用户在数组中查找不存在的值或访问数组中未定义的索引,我想实现自己的异常来处理。

int[] myIntArray = {1,2,3};
myIntArray[4] = ?? // this invoke ArrayIndexOutOfBoundsException 

所以我真正想做的就是这样:

  try{
     System.out.println("Access element:" + a[4]);
  }catch(ArrayIndexOutOfBoundsException e){
     // call my own exception witch I create in a new class
  } 

有些这样:

public class myException extends Exception
{
   public invalideIndexException()
   {

   } 
}

我是编程新手,Java文档很有帮助,但我仍然对实现这一点感到困惑。

1 个答案:

答案 0 :(得分:2)

你应该试试

try{
     System.out.println("Access element:" + a[4]);
  }catch(ArrayIndexOutOfBoundsException e){
     throw new CustomArrayIndexOutOfBoundException("blah blah"); // here
  } 

在捕获ArrayIndexOutOfBoundsException

后抛出您自己的异常
class CustomArrayIndexOutOfBoundException extends Exception{  
 CustomArrayIndexOutOfBoundException(String s){  
  super(s);  
 }  
}  
相关问题