Java自定義異常


自定義異常

 

1、繼承類

   

 

一般會選擇繼承ExceptionRuntimeException,如果不要求調用者一定要處理拋出的異常,就繼承RuntimeException

 

2、自定義異常類構造方法

 

 

代碼實例:

  People實體類

public class People {
    String name="";
    int age=0;
    String sex;
    public String getSex()
    {
        return sex;
    }
    public void setSex(String sex) throws Exception{
        if("男".equals(sex) || "女".equals(sex))
        {
            this.sex=sex;
        }
        else {
            throw new GendorException("性別必須是男或者女");
        }
    }
}

 自定義異常類

public class GendorException extends Exception {
    public GendorException(String msg)
    {
        super(msg);
    }
}

測試

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
            People p=new People();
            try {
                p.setSex("Male");
            } catch (Exception e) {
                System.out.println("設置性別出錯了");
                e.printStackTrace();//輸出異常信息
            }
    }

}

效果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM