创建公共类Exception250,声明一维数组,解决数组下标越界异常,用Java完成
时间: 2025-02-15 09:15:53 浏览: 31
创建一个名为`Exception250`的公共类,通常用于自定义异常处理特定错误,比如数组下标越界。下面是如何使用这个自定义异常,并处理数组下标的例子:
```java
public class Exception250 extends Exception {
public Exception250(String message) {
super(message);
}
}
public class ArrayExample {
private int[] myArray;
// 构造函数初始化数组
public ArrayExample(int size) {
if (size < 0) {
throw new Exception250("Array size cannot be negative.");
}
myArray = new int[size];
}
// 定义访问数组元素的方法,包含异常处理
public int get(int index) throws Exception250 {
if (index < 0 || index >= myArray.length) {
throw new Exception250("Array index out of bounds.");
}
return myArray[index];
}
public static void main(String[] args) {
try {
ArrayExample array = new ArrayExample(5); // 创建数组实例
System.out.println(array.get(0)); // 正确获取
System.out.println(array.get(-1)); // 将抛出异常,因为-1是下标越界
} catch (Exception250 e) {
System.out.println("Caught " + e.getMessage());
}
}
}
```
在这个示例中,我们首先定义了一个`Exception250`,然后在`get()`方法里检查了索引是否合法。如果索引超出范围,就抛出这个自定义异常。在`main()`方法中,我们捕获并打印了这个异常。
阅读全文
相关推荐


















