• 自定义异常



    * 自定义异常:如果JDK中异常类型无法满足程序需要。
    * 步骤:
    * 1.编写自定义异常类:继承Exception或RuntimeException
    * 2.编写构造方法,继承父类的实现
    * 3.实例化自定义异常对象
    * 4.使用throw抛出

    例:

    public class SexException extends Exception{
    public SexException(String message){
    super(message);
    }
    }

    public class TestSexException {
    public static void main(String[] args) {
    Student student = new Student();
    student.setName("张三");
    try {
    student.setAge(200);
    student.setSex("男");
    } catch (SexException e) {
    // e.printStackTrace();
    System.err.println(e.getMessage());
    }catch(AgeException e){
    System.err.println(e.getMessage());
    }finally{
    System.out.println("设置完成!");
    }
    System.out.println(student);

    }
    }

    public class Student {
    private String name;
    private int age;
    private String sex;
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }

    public int getAge() {

    return age;

    }

    public void setAge(int age) throws AgeException{

    if(age>=1&&age<=100){

    this.age = age;

    }else{

    throw new AgeException("年龄必须在1~100之间!");

    }

    }

    public String getSex() {

    return sex;

    }

    public void setSex(String sex) throws SexException{

    if(sex.equals("男")||sex.equals("女")){

    this.sex = sex;

    }else{

    throw new SexException("性别必须为男或女");

    }

    }

    @Override

    public String toString() {

    return "Student [name=" + name + ", age=" + age + ", sex=" + sex + "]";

    }

    }

     

  • 相关阅读:
    安装python包
    在RHEL5.4上升级Python
    IronPython开发Windows Form程序总结
    Windows下手动配置Oracle Client的要点
    dreampie一个很不错的python命令行交互工具
    Eclipse插件汇总
    pyDbRowFactory Python版Db Row Factory
    如何让Jython自动加载一个Jar包
    跨计算机执行的几个方法
    Python 版 Instance Activator
  • 原文地址:https://www.cnblogs.com/benpaozhimeng/p/6973637.html
Copyright © 2020-2023  润新知