【问题标题】:user-defined exception for ArrayIndexOutOfBoundsExceptionArrayIndexOutOfBoundsException 的用户定义异常
【发布时间】:2016-10-07 15:37:49
【问题描述】:

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

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 文档很有帮助,但我仍然对实现这一点感到困惑。

【问题讨论】:

  • 您可以在catch 中执行throw new MyException();

标签: java arrays exception


【解决方案1】:

你应该试试

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);  
 }  
}  

【讨论】:

  • 是否可以在CustomArrayIndexOutOfBoundException("-------");里面写一条消息
  • 最后一个问题,是否可以在 CustomArrayIndexOutOfBoundException 类中放置多个异常来处理用户正在查找的元素不存在和无效索引等异常。
  • @Cyber​​Allien 不,只有一个例外。 “您要查找的索引不存在或无效”。但是如果你想真正检查它是否无效,你可以用 if 条件检查索引的有效性,你可以从那里抛出。
  • 我想在找不到元素且索引无效时抛出异常。
  • 两者都导致 ArrayIndexOutOfBoundsException。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-16
  • 2021-11-16
  • 2016-09-10
  • 2011-08-30
  • 1970-01-01
  • 1970-01-01
  • 2011-04-14
相关资源
最近更新 更多