异常类使用

使用环境

今天想学习集中排序算法,在手动添加输入的时候想起为了使用代码起来更佳的流畅、正规;我需要使用异常类来判断输入是否为,符合规定的数字。如果不合规定则抛出异常



前言

为什么要使用异常? 1. 能让程序正常结束 2. 了解错误信息

一、自带异常类

1.1 示例

public class main {
    
    
    public static void main(String[] args){
    
    
        System.out.println("请输入想要排序的数组");
        Scanner input = new Scanner(System.in);
        String a = input.nextLine();
        List<Integer> arr = new ArrayList<Integer>();

            while (a.equals("err")== false) {
    
    
                try {
    
    
                    arr.add(Integer.parseInt(a));
                }catch (Exception e){
    
    
                    System.out.println("异常:输入为非数字"+e.getMessage());
                    break;
                }
                a = input.nextLine();
            }
        System.out.println(arr.toString());
    }
    }

输出结果为:
请输入想要排序的数组
2
3
sw
异常:输入为非数字For input string: “sw”
[2, 3]

Process finished with exit code 0

1.2 具体操作

try{
    
    
可能会出问题的代码
}
catch(Exception1 e){
    
    // Exception是所有异常的父类 , 异常后走catch进行异常处理
System.out.println("异常:输入为非数字"+e.getMessage());
}
catch(Exception2 e){
    
    // Exception是所有异常的父类 , 异常后走catch进行异常处理
System.out.println( +e.getMessage());
}

二、自定义异常类

在大型项目中通常自己定义异常类
1、使用Exception类定义用户自己的异常类
2、规定哪些方法产生这种异常就在这个类后Throws抛出该异常类。

  • 定义异常类
public class IntegerException extends Exception {
    
    

    //异常信息
    private String message;

    // 构造函数
    IntegerException(String message) {
    
    
        super(message);//意思是带着子类的构造函数的参数message调用父类的构造函数。
        this.message = "输出"+message+"不合理";
        throwMessage(this.message);

    }

    // 因为构造方法不能输出、则定义方法发布会信息
    public void throwMessage(String message) {
    
    
        System.out.println(message);

    }
 
}
  • 定义被异常类修饰的方法:写在Service层
    public static List addtoarr(List<Integer> arr, String input) throws IntegerException {
    
    
        if (isNumeric0(input)) {
    
    
            arr.add(Integer.parseInt(input));
        } else {
    
    //调用异常方法
                throw new IntegerException(input);
        }


        return arr;
    }
  • 在main方法中调用该修饰的方法 中使用
        try {
    
    
            addtoarr(arr, a);
        } catch (IntegerException e) {
    
    
            System.out.println(e.toString());
        }

总结

自定义异常类感觉也有点麻烦。。。。 以后在慢慢体会其中的精髓吧。

Guess you like

Origin blog.csdn.net/qq_36737214/article/details/117663532