自定义异常

1.自定义异常继承Exception,需继承父类Exception的无参构造和有参构造,自定义异常方法。

public class MyException extends Exception {
    public MyException(){
        super();
    };

    public MyException(String message){
        super(message);
    }

    public void validate(String input) throws MyException {
        if(input.equals("abc")){
            throw new MyException("输入不合法");
        }
    }
}

2.编写测试类

 1 import java.util.Scanner;
 2 
 3 public class Test {
 4     public static void main(String[] args){
 5         MyException myException = new MyException();
 6         Scanner sc = new Scanner(System.in);
 7         String input = sc.next();
 8         try {
 9             myException.validate(input);
10         }catch (MyException e){
11             e.printStackTrace();
12         }
13 
14 
15 
16     }
17 }

3.结果输出

原文地址:https://www.cnblogs.com/WhiperHong/p/11474943.html