gpt4 book ai didi

java - ArrayIndexOutOfBoundsException 的用户定义异常

转载 作者:行者123 更新时间:2023-11-30 08:36:32 25 4
gpt4 key购买 nike

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

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

最佳答案

你应该试试

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

关于java - ArrayIndexOutOfBoundsException 的用户定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37684365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com