手动使用throw抛出异常

/*
模拟注册
*/


public class fuck9{

public static void main(String [] args){

//假如用户提供的用户名如下:
String username="wwwwwwww";

//注册
CustomerService cs=new CustomerService();

try {

cs.register(username);

}catch(Illegalnameexception e){

System.out.println(e.getMessage());
}
}

}




//和顾客相关的业务
class CustomerService{

//对外提供一个注册的方法
public void register(String name) throws Illegalnameexception{

//完成注册
if(name.length()<6){

//异常,创建异常对象
throw new Illegalnameexception("用户名长度不能少于6位");
}

//如果代码能执行到此处,证明用户名是合法的
System.out.println("注册成功");

}

}




/*
自定义"无效名字异常"
1.编译时异常,直接继承Exception
2.运行时异常,直接继承runtimeException
*/
class Illegalnameexception extends Exception{//编译时异常
//class Illegalnameexception extends runtimeException{//运行时异常


//定义异常一般提供两个构造方法
public Illegalnameexception(){}

public Illegalnameexception(String msg){
super(msg);
}
}

猜你喜欢

转载自blog.csdn.net/rolic_/article/details/80232927