/**
* 功能描述:自定义异常
*
* @author 顾英明
* @date 2022/12/08 20:14
*/
/*
1、 自定义异常 NotFundException 类。
编写一个类,在此类中定义一个在某个数组查找目标对象的方法,在定义此方法过程中使用以上定义的异常类.
当在某范围内(数组)查找给定的目标对象找不到时抛出此异常类对象,从而使程序走向异常处理程序代码
*/
public class NotFoundException extends Throwable {
public NotFoundException() {
}
public NotFoundException(String message) {
super(message);
}
}
测试类:
/**
* 功能描述:测试类
* @author 顾英明
* @date 2022/12/08 20:18
*/
public class Test {
public static void main(String[] args) {
String[] arr = {"123", "234"};
try {
Test.search("3", arr);
} catch (NotFoundException e) {
// e.printStackTrace();
System.out.println(e.getMessage());
}
}
public static Boolean search(String number, String[] arr) throws NotFoundException {
for (String s : arr) {
if (number.equals(s)) {
return true;
}
}
throw new NotFoundException("目标元素不存在");
}
}
运行结果:
目标元素不存在
文章创建了一个名为NotFoundException的自定义异常类,该异常在数组中搜索目标对象未找到时抛出。在Test类的main方法中,尝试搜索数组中的特定数字,如果找不到则捕获并打印NotFoundException的错误消息。
653

被折叠的 条评论
为什么被折叠?



