⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 person3.java

📁 《Java2程序设计实用教程(第2版)》课件
💻 JAVA
字号:
//【例5.7】  自定义异常类。

public class Person3
{
    protected String name;               //姓名
    protected int age;                   //年龄

    public Person3(String name,int age) throws IllegalAgeException
    {
        this.set(name);
        this.set(age);
    } 

    public void set(String name)
    {
        if (name==null || name=="")
            this.name = "姓名未知";
        else
            this.name = name;
    }
            
    public void set(int age) throws IllegalAgeException
    {
        if (age>=0 && age<100)
            this.age = age;
        else
            throw new IllegalAgeException(""+age); 
    }

    public void set(String name, int age) throws IllegalAgeException
    {
        this.set(name);
        this.set(age);
    }
            
    public String toString() 
    {
        return this.name+","+this.age+"岁";
    }
    
    public void print()
    {
        System.out.println(this.toString());
    }

    public static void main(String args[])
    {
        Person3 p1=null;
        try
        {
            p1 = new Person3("李小明",20);  //调用声明抛出异常的方法,必须写在try语句中,否则编译不通过
            p1.set(121);
        }
        catch(IllegalAgeException e)        //捕获自定义异常类,而非Exception类
        {
            e.printStackTrace();            //显示异常栈跟踪信息
        }
        finally
        {
            p1.print();
        }
    }
}

/* 
程序运行结果如下:

IllegalAgeException: 121
            at Person2.set(Person2.java:29)
            at Person2.main(Person2.java:53)

李小明,20岁


    
*/

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -