📄 person2.java
字号:
//【例5.5】 抛出自定义异常对象。
//【例5.6】 声明抛出异常的方法与方法调用者处理异常。
public class Person2
{
protected String name; //姓名
protected int age; //年龄
public Person2(String name,int age) throws Exception //构造方法声明抛出异常
{ //因为无法处理set()方法抛出的异常,再向上传递set()方法抛出的异常
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 Exception //声明方法抛出异常
{
if (age>=0 && age<100)
this.age = age;
else
throw new Exception("IllegalAgeData: "+age);
}
public void set(String name, int age) throws Exception
{
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[]) throws Exception
{
Person2 p1 = new Person2("李小明",20);
p1.print();
p1.set(121);
p1.print();
}
}
/*
程序运行结果如下:
李小明,20岁
Exception in thread "main" java.lang.Exception: IllegalAgeData: 121
at Person2.set(Person2.java:29)
at Person2.main(Person2.java:53)
*/
/*
public Person2(String name) throws Exception
{
this(name,0);
}
public Person2() throws Exception
{
this("姓名未知",0);
}
public Person2(Person2 p1) throws Exception
{
this(p1.name, p1.age);
}
public void set(int age) //原始
{
if (age>0 && age<100)
this.age = age;
else
this.age = 0;
}
public void set(int age)
{
if (age>0 && age<100)
this.age = age;
else
throw new Exception("IllegalAgeData"); //抛出异常
}
public void set(int age)
{
try
{
if (age>0 && age<100)
this.age = age;
else
throw new Exception("IllegalAgeData"); //抛出异常
}
catch(Exception e)
{
System.out.println(e.toString()); //虽然捕获到了异常但不能处理,this.age仍没有值
}
}
public void set(Person2 p1) throws Exception
{
this.set(p1.name);
this.set(p1.age);
}
public static void main(String args[])
{
try
{
Person2 p1 = new Person2("李小明",20); //调用声明将抛出异常的方法,必须写在try语句中,否则编译不通过
p1.print();
p1.set(121);
p1.print();
}
catch(Exception e)
{
System.out.println(e.toString()); //捕获到了异常
}
}
程序运行结果如下:
李小明,20岁
java.lang.Exception: IllegalAgeData: 121
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -