1、對於java中的異常使用try{}catch{}捕獲時,要判斷哪些代碼可能出錯只對那部分代碼進行捕獲,避免捕獲太多代碼影響性能。
2、必須避免空指針異常
正例:if(obj!=null){}
反例:try{obj.method()}catch{}
3、對於內部系統的異常情況,使用自定義異常進行拋出,在最外層進行捕獲。例如某個參數爲空,自定義一個異常,然後進行拋出。
public class CustomerException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String msg;
private int code = 500;
public CustomerException (String msg) {
super(msg);
this.msg = msg;
}
public CustomerException (String msg, Throwable e) {
super(msg, e);
this.msg = msg;
}
public RRException(String msg, int code) {
super(msg);
this.msg = msg;
this.code = code;
}
public CustomerException (String msg, int code, Throwable e) {
super(msg, e);
this.msg = msg;
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
在spring中可以使用@RestControllerAdvice @ExceptionHandler建立異常處理器CustomerExceptionHandler對拋出的各類異常統一捕獲處理而不用在代碼中編寫try{}catch{}
@RestControllerAdvice
public class CustomerExceptionHandler{
// @ExceptionHandler中的參數表明需要捕獲什麼異常
@ExceptionHandler(CustomerException.class)
public ResultObject<Object> HandlerCustomerException()
{
.......
}
@ExceptionHandler(Exception.class)
public ResultObject<Object> HandlerException()
{
}
}
4、異常必須進行區分,禁止直接捕獲exception 。
5、異常捕獲後要對異常進行處理。