Java异常以及处理

image

 异常捕获:

image

 异常中的方法:

image

 

image

 

image

自定义异常

image

 

image

 

image

 

image

 

 

image

 

// 自定义异常类(只负责存储错误信息)
class ArrayLengthNotZeroException extends Exception {
public ArrayLengthNotZeroException(String message) {
super(message);
}
}

// 单独的工具类负责判断逻辑
class ArrayValidator {
public static void checkArray(int array[]) throws ArrayLengthNotZeroException {
if (array.length == 0) {
throw new ArrayLengthNotZeroException("数组长度不能为0");
}
System.out.println("数组长度正确: " + array.length);
}
}

// 使用
public class Demo {
public static void main(String[] args) {
try {
int array[] = {};
ArrayValidator.checkArray(array); // 调用工具类方法
} catch (ArrayLengthNotZeroException e) {
System.out.println(e.getMessage());
}
}
}

posted @ 2025-09-27 15:51  jokercheems  阅读(5)  评论(0)    收藏  举报