程序功能:
用年龄、姓名参数创建一个Person类对象,并输出该对象的年龄。
Exception类的应用:
输出的年龄范围可能产生错误,需要控制年龄范围。
若年龄正常,则仅执行try中语句
若年龄异常,则执行catch中语句:输出出现异常的原因和位置。
我的理解:
可能产生异常的方法testAge(int),在执行时有两种情况分支:
if(异常情况条件){在方法中throw异常对象;在main方法catch;printStackTrace();处理异常}
else{正常执行}
两种情况的输出:
异常情况:Person p = new Person("小明",9000); testAge(p.age);
正常情况:Person p = new Person("小明",90); testAge(p.age);
//自定义异常类
public class AgeException extends Exception
{
//只需要继承父类的带参构造方法(参数message为异常原因)
public AgeException(String message){
super(message); //调用了父类一个参数的构造函数
}
}
////////////////////////////////////////////////////////
//main方法所在类
public class Demo {
public static void main(String[] args)
{
try{//若年龄正常,则仅执行try中语句
Person p = new Person(200,"小明");
testAge(p.age);
}catch(AgeException e){
//若年龄异常,则执行catch中语句
e.printStackTrace();//printStackTrace()方法:输出出现异常的原因和位置
System.out.println("请重新输入年龄");//处理异常
}
}
public static void testAge(int age) throws AgeException{//可能产生异常的方法
//情况一(异常):抛出异常(并以异常产生原因为参)
if(age<0 || age >200){
throw new AgeException("年龄不正确");
}
//情况二(正常):
System.out.println("年龄正确");
}
}
//////////////////////////////////////////////////////////
//实体类
public class Person {
int age;
String name;
public Person(int age,String name){
this.age = age;
this.name = name;
}
}