实现图解:
下面是一个关于检验年龄是否合格的实例.用到继承及异常处理的相知识!
1~~~~~~~~~~~~~~~~~~~~~~
package age;
class AgreeException extends Exception {
int age;
AgreeException(int age, String s) {
super(s);
this.age = age;
}
AgreeException() {
super();
}
}
2~~~~~~~~~~~~~~~~~~~~~
class IllegalAgeException extends AgreeException {
IllegalAgeException(int age, String s) {
super(age, s);
}
IllegalAgeException() {
super();
}
}
3~~~~~~~~~~~~~~~~~~~~~~~
class OutlimitException extends AgreeException
{
int agelimit;
OutlimitException(int age,int agelimit,String s)
{
super(age,s);
this.agelimit=agelimit;
}
OutlimitException(){
super();
}
}
4~~~~~~~~~~~~~~~~~~~~~~~~
class NegativAagEexception extends IllegalAgeException {
NegativAagEexception(int age) {
super(age, "年龄不能为负数! ");
}
NegativAagEexception() {
super();
}
}
5~~~~~~~~~~~~~~~~~~~~~~~~
class OldException extends OutlimitException{
OldException(int age,int agelimit)
{
super(age,agelimit,"大于年龄限制");
}
OldException()
{
super();
}
}
6~~~~~~~~~~~~~~~~~~~~~~~
package age;
class YoungException extends OutlimitException{
YoungException(int age,int agelimit)
{
super(age,agelimit,"小于年龄限制");
}
YoungException()
{
super();
}
}
7~~~~~~~~~~~~~~~~~~~~~~~
public class Exceptiondemo {
static int lowlimit;
static int highlimit;
static void check(int age) throws NegativAagEexception, OutlimitException {
if (age < 0) {
throw new NegativAagEexception(age);
} else if (age < lowlimit) {
throw new YoungException(age, lowlimit);
} else if (age > highlimit) {
throw new OldException(age, highlimit);
}
System.out.println(age + " 年龄符合要求!");
}
public static void main(String[] args) {
int[] age = { -11, 16, 70, 12 };
highlimit = 60;
lowlimit = 15;
System.out.println("开始检测 :" + '/r' + age[0]);
for (int i = 0; i < age.length; i++) {
try {
check(age[i]);
} catch (NegativAagEexception e) {
System.out.println(e);
// e.printStackTrace();
} catch (OutlimitException e) {
System.out.println(e);
// e.printStackTrace();
} finally {
if (i < age.length - 1) {
System.out.println("待检测的年龄" + age[i + 1]+'/r');
}
}
}
}
}