java中继承及异常处理!

实现图解:

 

 

下面是一个关于检验年龄是否合格的实例.用到继承及异常处理的相知识!

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');
    }
   }
  }
 }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值