[Java][异常]自定义异常的设计逻辑与应用

发布时间:2023年12月19日
1.NameFormat是异常的名字 表示姓名格式化问题
2.Exception:表示当前类是一个异常类

//运行时:继承RuntimeException
//编译时:继承Exception
我们写自定义异常是为了更加的见名知意
编译时异常作用:提醒程序员去检查本地信息,比如链接本地数据库,检索本地文件
运行时异常:通常是参数错误导致的异常

——————————————————————————————————————

严格来说:我们所自定义的异常实际上大部分功能都源自于其继承的类

我们仅仅对其名字进行修改,令这个名字更加见名知意,同时提供一个可以修改的平台

public class NameFormatException extends RuntimeException{
    /*
    1.NameFormat是异常的名字 表示姓名格式化问题
    2.Exception:表示当前类是一个异常类

    //运行时:继承RuntimeException
    //编译时:继承Exception
    我们写自定义异常是为了更加的见名知意
    编译时异常作用:提醒程序员去检查本地信息,比如链接本地数据库,检索本地文件
    运行时异常:通常是参数错误导致的异常
     */

    public NameFormatException() {
    }

    public NameFormatException(String message) {
        super(message);
    }
}
public class AgeOutOfBoundsException extends RuntimeException
{
    public AgeOutOfBoundsException() {
    }

    public AgeOutOfBoundsException(String message) {
        super(message);
    }
}
public class Student
{
    int age;
    String name;

    public Student() {
    }

    public Student(int age, String name) {
        this.age = age;
        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+"年龄有误,年龄应该是18-40");
        }
        this.age = age;
    }

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

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

    public String toString() {
        return "Student{age = " + age + ", name = " + name + "}";
    }
}
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        /*
        需求:录入学生信息
        标准:年龄在18-40岁 名字长度在3个字符-10个字符
        否则报告异常
         */
        //创建录入对象

        Scanner sc = new Scanner(System.in);
        //创建学生对象
        Student s = new Student();
        //接受学生的年龄
        try {
            System.out.println("请你输入学生的年龄");
            String agestr = sc.nextLine();
            int age = Integer.parseInt(agestr);
            s.setAge(age);
            //接受学生的姓名
            System.out.println("请你输入学生的姓名");
            String name = sc.nextLine();
            s.setName(name);
        }catch (NameFormatException e){
            e.printStackTrace();
        }catch(AgeOutOfBoundsException e){
            e.printStackTrace();
        }

        //5.打印
        System.out.println(s);

    }
}

文章来源:https://blog.csdn.net/qq_37511412/article/details/135092873
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。