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();//输出异常信息
            }
    }

}

效果:

原文地址:https://www.cnblogs.com/schangxiang/p/11179314.html