最近写了不少业务代码,深感异常处理之重要性。异常处理好了,能让系统更加稳健、并易于寻找错误。在实践过程中,对于下面的代码:
try {
// do something
} catch (Exception e) {
// do nothing
}
这种应该是要深恶痛绝的,既然什么也不做,为什么要吞掉异常,直接抛出不就得了呗,这样出错了也好定位错误。有个Fail fast
原则, 程序中关键性的代码,比如数据库、redis、mq的连接出现异常,应用立即运行失败。再比如有些IOException
、FileNotFoundException
直接抛出得了,或者捕获之后加点异常描述信息之后也将异常抛出,程序出错了,能直接定位错误。
有异常并不是坏事,只是表明你写的程序或许有bug,还存在改进的地方。
再看一例:
public static String encodeString(String name) throws Exception {
return URLEncoder.encode(name, "UTF-8");
}
直接在方法上throws Exception
,这样出现异常后是直接抛出了,但还是不好。在其他的方法中调用这个encodeString
方法时,还要try catch
或 throws
, 这样其实是不方便的。
我们知道,RuntimeException
是不用定义throws
的,
所以可以为你的应用自定义一个runtime 异常:
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String errorCode;
public String getErrorCode() {
return errorCode;
}
/**
* 自定义运行时异常
*
* @param errorCode 业务自定义错误码
* @param message 必须是用户可读的错误信息
*/
public BusinessException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
/**
*
* @param message
*/
public BusinessException(String message) {
super(message);
}
}
然后在你的业务代码中:
public static String encodeString(String name) {
String res;
try {
res = URLEncoder.encode(name, "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new BusinessException("编码异常");
}
return res;
}
如果系统运行的时候有问题就抛出异常,在排解错误的时候会十分方便。