本文小编以用户登录为例,进行异常处理。
首先新建实体类User.java:
/**
* Created by why_768 on 2017/2/16.
*/
public class User {
int id;
String email;
String pwd;
public User(){
}
public User(int id,String email,String pwd){
super();
this.id=id;
this.email=email;
this.pwd=pwd;
}
@Override
public String toString(){
return id + "," + email;
}
@Override
public boolean equals(Object obj){
if(obj == null){
return false;
}
if(this == obj){
return true;
}
if(obj instanceof User){
User o=(User)obj;
return id == o.id;
}
return false;
}
@Override
public int hashCode(){
return id;
}
}
然后新建两种声明式异常:
/**
* Created by why_768 on 2017/2/16.
* 该类表示用户已经注册过异常
*/
public class UserExistsException extends Exception{
public UserExistsException(String message){
super(message);
}
}
/**
* Created by why_768 on 2017/2/16.
* 该类表示用户或密码错误异常
*/
public class EmailOrPwdException extends Exception {
public EmailOrPwdException(String message){
super(message);
}
}
创建用户管理类UserManager:
import java.util.HashMap;
import java.util.Map;
/**
* Created by why_768 on 2017/2/16.
*/
public class UserManager {
//存储对象的集合,key是email,value是用户
private Map<String,User> users=new HashMap<String, User>();
private int id=1;
public User reg(String email,String pwd) throws UserExistsException{
if(users.containsKey(email)){
throw new UserExistsException("该邮箱" + email + "已存在");
}
User user=new User(id++,email,pwd);
users.put(email,user);
return user;
}
public User login(String email,String pwd) throws EmailOrPwdException{
if(!users.containsKey(email)){
throw new EmailOrPwdException("无此用户!");
}
User user=users.get(email);
if(!user.pwd.equals(pwd)){
throw new EmailOrPwdException("密码错误!");
}
return user;
}
}
建立测试类:
public class Main {
public static void main(String[] args) throws Exception{
UserManager mgr=new UserManager();
User user=mgr.reg("why_768@163.com","123");
System.out.println("注册成功!");
//测试1,重复注册,出现异常
user=mgr.reg("why_768@163.com","123");
//测试2,登录密码错误,出现异常,密码不对
user=mgr.login("why_768@163.com","1233");
//测试3,登录成功!
User someone=mgr.login("why_768@163.com","123");
System.out.println(someone);
}
}
总结:
代码调用抛出异常的方法,必须处理异常,有两种方式:
1、使用try catch finally 捕获
2、直接再抛出异常
处理异常的方式依赖具体业务逻辑,可灵活处理。