Java 自訂異常類

來源:互聯網
上載者:User

標籤:sys   check   bsp   trace   異常   exception   user   cep   system   

類1:public class LogicException extends RuntimeException {
    //商務邏輯異常
    /**
     *
     * @param message 異常資訊
     */
    public LogicException(String message) {
        super(message);
    }
    /**
     *
     * @param message 異常資訊
     * @param cause  當前異常的根本原因
     */
        public LogicException(String message, Throwable cause) {
            super(message, cause);
        }
    
}
類2:private static String[] arr={"張三","小張","小明","李四"};
    public static void main(String[] args) {
        try {
            checkUsername("張三");
        } catch (LogicException e) {
            String errorMsg=e.getMessage();
            System.out.println("給使用者看"+errorMsg);
        }
        
    }
    private static Boolean checkUsername(String username){
        for (String name : arr) {
            if(name.equals(username)){
                throw new LogicException("很抱歉,"+username+"已經註冊了!");
            }
        }
        System.out.println("註冊成功!");
        return true;
    }

}
[總結] 1.自訂異常: class 異常類名 extends Exception { public 異常類名(String msg) { super(msg); } } 2.標識可能拋出的異常: throws 異常類名1,異常類名2 3.捕獲異常: try{} catch(異常類名 y){} catch(異常類名 y){} 4.方法解釋 getMessage() //輸出異常的資訊 printStackTrace() //輸出導致異常更為詳細的資訊

 

Java 自訂異常類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.