自学内容网 自学内容网

Java异常(小练习)

自定义异常

//技巧

//NameFormat 当前异常的名字,表示姓名格式化问题

//Exception 表示当前类是一个异常类

//运行时异常:RuntimeException 核心 由于参数错误的异常

//编译时异常:Exception核心 提醒程序员检查本地信息

NameFormatException

package function;

public class NameFormatException extends RuntimeException {
    //技巧
    //NameFormat 当前异常的名字,表示姓名格式化问题
    //Exception 表示当前类是一个异常类
    //运行时异常:RuntimeException 核心 由于参数错误的异常
    //编译时异常:Exception核心 提醒程序员检查本地信息

    public NameFormatException() {
    }

    public NameFormatException(String message) {
        super(message);
    }
}

AgeOutOfBoundsException

package function;

public class AgeOutOfBoundsException extends RuntimeException {
    public AgeOutOfBoundsException() {
    }

    public AgeOutOfBoundsException(String message) {
        super(message);
    }
}

GirlFriend

package function;

public class GirlFriend {
    private String name;
    private int age;

    public GirlFriend() {
    }

    public GirlFriend(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     *
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     *
     * @param name
     */
    public void setName(String name) {
        int len = name.length();
        if (len < 2 || len > 10) {
            throw new NameFormatException(name+" 格式有误,长度应为:2~10");
        }
        this.name = name;
    }

    /**
     * 获取
     *
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     *
     * @param age
     */
    public void setAge(int age) {
        if(age<18 || age>40){
            throw new AgeOutOfBoundsException(age+"年龄不在范围内");
        }
        this.age = age;
    }

    public String toString() {
        return "GirlFriend{name = " + name + ", age = " + age + "}";
    }
}

Test

package function;

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        GirlFriend gf = new GirlFriend();
        while (true) {
            try {
                System.out.println("请输入心仪女朋友的名字");
                String name = sc.nextLine();
                gf.setName(name);
                System.out.println("请输入心仪女朋友的年龄");
                String ageStr = sc.nextLine();
                int age = Integer.parseInt(ageStr);
                gf.setAge(age);
                break;
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }catch (NameFormatException e) {
                e.printStackTrace();
            }catch (AgeOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
        System.out.println(gf);
    }

}

意义:就是为了让控制台的报错信息更加的见名思意


原文地址:https://blog.csdn.net/qq_63126439/article/details/142365630

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!