public static String changeF2Y(String amount) throws Exception {
amount = amount.trim();
if (!amount.matches(CURRENCY_FEN_REGEX)) {
throw new Exception("金额格式有误");
}
amount = BigDecimal.valueOf(Long.valueOf(amount)).divide(new BigDecimal(100)).toString();
if(!amount.contains(".")){
amount = amount + ".00";
}
return amount;
}
去掉throws,直接将可能出现异常的地方放置try-catch中。
示例代码:
public static String changeF2Y(String amount) {
try{
amount = amount.trim();
if (!amount.matches(CURRENCY_FEN_REGEX)) {
throw new Exception("金额格式有误");
}
amount = BigDecimal.valueOf(Long.valueOf(amount)).divide(new BigDecimal(100)).toString();
if(!amount.contains(".")){
amount = amount + ".00";
}
}catch(Exception e){
e.printStackTrace();
}
return amount;
}
这不是矛盾么?既然throw了,干嘛要catch
既然要catch干嘛要throw,自己抛自己接好玩么?
当然也不是不可以,
throw new Exception("金额格式有误");
->
try
{
throw new Exception("金额格式有误");
}
catch (Exception ex)
{
//又抓回来咯
}
底层的话最好就往上抛,到了顶层的时候就try catch