帮我写一个自定义数组异常的代码
时间: 2024-05-05 13:20:50 浏览: 9
好的,以下是一个自定义数组异常的代码示例:
```java
public class CustomArrayException extends Exception {
public CustomArrayException(String message) {
super(message);
}
}
public class CustomArray {
private int[] array;
private int size;
public CustomArray(int size) {
this.array = new int[size];
this.size = size;
}
public void setElement(int index, int value) throws CustomArrayException {
if (index < 0 || index >= size) {
throw new CustomArrayException("Invalid index: " + index);
}
array[index] = value;
}
public int getElement(int index) throws CustomArrayException {
if (index < 0 || index >= size) {
throw new CustomArrayException("Invalid index: " + index);
}
return array[index];
}
}
```
在上面的代码中,`CustomArrayException` 继承自 `Exception` ,代表自定义数组异常。`CustomArray` 类中的 `setElement` 和 `getElement` 方法都会抛出 `CustomArrayException` 异常,如果索引值不在数组范围内,将会抛出异常。在使用 `CustomArray` 类的时候,需要使用 `try-catch` 语句来处理异常。例如:
```java
CustomArray array = new CustomArray(5);
try {
array.setElement(6, 10); // 抛出 CustomArrayException 异常
} catch (CustomArrayException e) {
System.out.println(e.getMessage()); // 输出 "Invalid index: 6"
}
```