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

    效果:

  • 相关阅读:
    dnsever 邮件记录
    用于显示上个月和下个月_PHP
    JSON学习
    ASP生成新会员编号
    godaddy_关于产品退款
    Switch Case语句中多个值匹配同一个代码块的写法
    网闸与防火墙的比较
    bench.sh 跑分测速
    Kcptun加速SS
    linux 安全狗
  • 原文地址:https://www.cnblogs.com/schangxiang/p/11179314.html
Copyright © 2020-2023  润新知