person3.java
来自「这是《Java2程序设计实用教程(第2版)》教材中附带的例题源代码。」· Java 代码 · 共 77 行
JAVA
77 行
//【例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 + =
减小字号Ctrl + -
显示快捷键?