Java第二次作业第五题

自定义异常类,非法年龄类,并在person3类中使用此类,根据情况抛出异常,并进行处理。

package naizi;

class IllegalAgeException extends Exception{    //无效年龄异常类
public IllegalAgeException(String s){
	super(s);
}
public IllegalAgeException(){
	this("");
}
}

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(Integer.toString(age));   //抛出IllegalAgeException的类
}
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();		
	}	
}
}  

运行结果如图:

Java第二次作业第五题