
自定义异常,这个搞懂了就知道什么时候catch什么时候throw,什么时候throws
/*
自定义“无效名字异常”.
1.编译时异常,直接继承Exception
2.运行时异常,直接继承RuntimeException
*/
public class IllegalNameException extends Exception{ //编译时异常
//public class IllegalNameException extends RuntimeException{ //运行时异常
//定义异常一般提供两个构造方法
public IllegalNameException(){}
public IllegalNameException(String msg){
super(msg);
}
}
//顾客相关的业务
public class CustomerService{
//对外提供一个注册的方法
public void register(String name) throws IllegalNameException{
//完成注册
if(name.length()<6){
//异常
//创建异常对象
//IllegalNameException e = new IllegalNameException("用户名长度不能少6位");
//手动抛出异常
//throw e;
throw new IllegalNameException("用户名长度不能少6位");
}
//如果代码能执行到此处,证明用户名是合法的.
System.out.println("注册成功!");
}
}
/*
模拟注册
*/
public class Test{
public static void main(String[] args){
//假如用户提供的用户名如下
String username = "fdafdafdsa";
//注册
CustomerService cs = new CustomerService();
try{
cs.register(username);
}catch(IllegalNameException e){
System.out.println(e.getMessage());
}
}
}
1511

被折叠的 条评论
为什么被折叠?



