java 异常处理规范


最近架构升级,对java 异常处理机制做了一定的整理

规范是大家一致认可后,并遵循的。

附件是我认为合理的异常处理机制,大家可以参考下,提出更合理的建议,我们大家一致遵循,使之成为规范

欢迎拍砖

1:首先是dao层,一般不做异常的具体处理,直接外网抛

/**
*
*/
package com.tech.sandu.Exception;

import java.sql.SQLException;

/**
* @author timy.liu 模拟链接数据库,查询一个电商用户一年消费的总金额和购物次数,最后求出平均每次消费金额
*/
public class UserDao {
/**
* 获取一个用户购物的总金额
*
* @param manId
* @return
*/
public long getTotalFeePerMan(String manId) {
return 8888;
}

/**
* 获取一个用户的购物次数
*
* @param manId
* @return
* @throws SQLException
*/
public int getShoppingTimesPerMan(String manId) throws SQLException {
int shoppingTimes = 0;
int random = (int) (Math.random() * 10);
System.out.println(random);
if (random < 5){
throw new SQLException("");
}

shoppingTimes=random;
return shoppingTimes;
}

}


2:其次是service,需要对异常做具体处理

/**
*
*/
package com.tech.sandu.Exception;

import java.sql.SQLException;

/**
* @author timy.liu
*模拟链接数据库,查询一个电商用户一年消费的总金额和购物次数,最后求出平均每次消费金额
*业务层处理异常,不再外抛到controller层
*/
public class UserService {
private UserDao userDao=new UserDao();
public float getAverageFeeByMan(String manId){
float averageFee=0f;
long totalFee = userDao.getTotalFeePerMan(manId);
int shoppingTimes =0;
try {
shoppingTimes = userDao.getShoppingTimesPerMan(manId);
} catch (SQLException e) {
System.out.println(manId+"_get_shopping_times_exception_"+e.getMessage());
e.printStackTrace();
/**
* 此时出异常需要考虑是否对异常进行修复,如果此时不对异常进行修复,那程序运行40%的会出异常,
* 60%的机会是正确的,这就是我们代码有时正常有时异常的原因之一,
* */
//********异常修复开始***********
//根据需求,出现该异常时,默认该用户平均购物金额为0;直接放回,程序不再往下跑了。此时异常有抛出,同时程序不会中断,而是继续执行
return 0;
//********异常修复结束***********
}
averageFee = totalFee/shoppingTimes;
return averageFee;
}
}

3:最后是controller层,不需要对异常进行处理,因为service层已经处理好了

/**
*
*/
package com.tech.sandu.Exception;

/**
* @author timy.liu
*
*/
public class UserController {
private static UserService userService = new UserService();

/**
* @param args
*/
public static void main(String[] args) {
for(int i=0;i<10;i++){
System.out.println("test_times_"+i+"_"+userService.getAverageFeeByMan("ABCDEF"));
}

}

}

猜你喜欢

转载自blog.csdn.net/timy07/article/details/74046548