这个例子主要是帮自己存一下关于自定义异常的基础用法,以免长时间不用都忘了怎么用,废话不多说,下面贴代码。
共两个java文件
1、TestE类
public class testE{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("请输入手机号:");
String phone = scanner.next();
System.out.println("请输入密码:");
String password = scanner.next();
try {
register(phone,password);
} catch (MobileException e) {
e.printStackTrace();
}
System.out.println("ss");
String s = scanner.next();
}
public static void register (String phone,String pass) throws MobileException{
if(phone.length()!=11){
throw new MobileException("手机号位数不对!");
}else{
if(!Pattern.matches("1[35789]\\d{9}",phone)){
throw new MobileException("手机号格式不正确!");
}
}
}
}
2、MobileException类
public class MobileException extends Exception {
public MobileException(){
super();
}
public MobileException(String msg){
super(msg);
}
}
如果有不对的请多指教,主要是给自己记着,忘记了也好快速捡起来。