自定义异常
当Java提供的异常不适用,需要自己再添加异常时
格式:
public class xxxException extends Exception | RuntimeException{
添加一个空参数构造方法
添加一个含异常信息的构造方法
}
注意点:
1、自定义异常类名称以Exception结尾,说明是异常类
2、自定义异常类必须继承Exception或RuntimeException
继承Exception是编译期异常
继承RuntimeException是运行期异常
举例:
public class RegisterException extends Exception{ //自定义的注册异常
public RegisterException(){
super();
}
public RegisterException(String message){
super(message);
}
}
/*
* 输入一个名字,进行检查,如果数组(数据库)中已经有此用户,则报错:RegisterException
*/
public class DemoCustomizeException {
public static void main(String[] args) throws RegisterException {
Scanner sc = new Scanner(System.in); //输入
System.out.println("请输入注册的名字:");
String name = sc.next();
checkException(name);
}
public static void checkException(String name) throws RegisterException { //检查名字是否重复
String[] names = {"张三", "李四", "王五"};
for (String s : names) {
if (name.equals(s)) {
throw new RegisterException("该名称已被注册,重新输入"); //抛出自定义异常
}
}
System.out.println("恭喜!注册成功");
}
}