自定义异常类

格式:

public class xxxException extends Exceptin/RunTimeException{

添加一个空参构造方法;

添加一个带有异常信息的构造方法;

}

继承Exception就是一个编译期异常;继承RunTimeException就是一个运行期异常。

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

    public PersonalException(String message ){
        super(message);
    }
import java.util.Scanner;

public class Practice {
    public static void main(String[] args) {
        String[] str1 = {"张三", "李四", "王五"};
        System.out.println("请输入用户名");
        Scanner sc = new Scanner(System.in);
        String name = sc.next();try {
            throw new PersonalException("该用户已被注册");
        }catch(PersonalException e){
            e.getStackTrace();
        }

        method(str1,name);

    }
    public static void method(String[] str1 ,String name)  {
        for(String str : str1){
            boolean b = name.equals(str);
            if (b) {
                try {
                    throw new PersonalException("该用户已被注册");
                } catch (PersonalException e) {
                    System.out.println( e.toString());
                }
                return;
            }
        }
        System.out.println("注册成功!");

    }
}
原文地址:https://www.cnblogs.com/susexuexi011/p/13903824.html