zoukankan      html  css  js  c++  java
  • 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();//输出异常信息
                }
        }
    
    }

    效果:

  • 相关阅读:
    微服务全链路剖析
    记一次被挖矿经历
    centos权限总结
    Beizer。。。。。
    遇到的几个算法
    程序截图
    CFileViewer(文件浏览器)
    框架设计
    git常用代码
    右值引用
  • 原文地址:https://www.cnblogs.com/schangxiang/p/11179314.html
Copyright © 2011-2022 走看看