自定義異常及枚舉類使用

自定義異常

理解error、RuntimeException(運行時,虛擬機報的錯)和非RuntimeException(編譯時,編譯器找出的錯)
    1.java中異常均繼承自Throwable,其有兩個重要的直接子類error與exception.
    2.java錯誤error,大部分是由虛擬機爆出來的錯誤,是程序沒法處理的錯誤,如OutOfMemoryError,當JVM須要更多內存空間而得不到知足時,就會爆出OutOfMemoryError。
    3.Exception,異常,其下分類不少,如可查異常與不可查異常,運行時異常與非運行時異常,基本概念同樣,只是說法不一樣罷了。其有個重要的子類即RuntimeException運行時異常,其它直接子類都歸爲非RuntimeException,如IOException,SQLException等。
        a.非RuntimeException是在代碼書寫時,編譯器給你檢查提示你要進行try catch或throws處理。
        b.RuntimeException,編譯器不會幫你自動檢查,當你運行程序時,虛擬機纔會給你爆出錯誤讓你去處理,這個每每是咱們編碼邏輯或不規範致使的前端


自定義異常,步驟,三步走
    1.繼承RuntimeException
    2.重載構造函數
    3.重寫方法
好比:
public class SellException extends RuntimeException{
1.繼承RuntimeException
    private Integer code; //異常碼,相似於狀態碼,前端根據code做相應處理
    public SellException(ResultEnum resultEnum) {2.重載構造函數
        super(resultEnum.getMessage());
        this.code = resultEnum.getCode();
}
     public SellException(Integer code, String message) {
        super(message);
        this.code = code;
}
}
用法:throw new SellException(ResultEnum.PRODUCT_NOT_EXSIT);java

使用枚舉對象封裝常量

枚舉對象爲enum類型,
步驟
    1.建立構造函數,參數爲常量值和常量含義
    2.建立枚舉對象
@Getter
public enum OrderStatusEnum implements CodeEnum {
    NEW(0, "新訂單"),
    FINISHED(1, "完結"),
    CANCEL(2, "已取消"),
;
    private Integer code;
    private String message;函數

    OrderStatusEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }
}this

相關文章
相關標籤/搜索