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