关于自定义异常和try的练习

练习要求:键盘录入女朋友的姓名和年龄,年龄范围在18~40之间,姓名长度在0~100之间,如果不符合条件就会重新录入到录入成功为止。

1.代码部分

public class GrilFrend {
    String name;
    int age;

    public void setName(String name) {
        if(name.length()>0&&name.length()<100&&name!=null){
            this.name=name;
        }else{
            throw new helloException();
        }
    }

    public void setAge(int age) {
        if(age>18&&age<40){
            this.age=age;
        }else{
            throw new helloException();
        }
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}
 

import java.util.Scanner;

public class 异常 {
    public static void main(String args[]){
        GrilFrend a=new GrilFrend();
        Scanner sc=new Scanner(System.in);
        while(true){
            try{
                System.out.print("请输入女朋友姓名:");
                a.setName(sc.nextLine());
                System.out.print("\n请输入女朋友年龄:");
                a.setAge(sc.nextInt());
                System.out.println("\n"+"女朋友年龄:"+a.age+"  女朋友姓名:"+a.name);
                break;
            }catch(helloException e){
                System.out.println("输入年龄或者姓名有错误");
            }
        }
    }
}

public class helloException extends RuntimeException{
    public helloException() {
    }

    public helloException(String message) {
        super(message);
    }
}

收获:

1.自定义异常的创建步骤。

2.如果自定义异常需要应用到try中需要自己手动trow抛出异常,才能够被捕获。

3.复习了scanner类

观看谨慎,总结可能存在错误,代码也不是很完善。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值