Java自定义异常

package a0418;

import a0418.Exception.AgeException;
import a0418.Exception.MathStringException;
import a0418.Exception.NameException;

import java.util.Scanner;

public class Test3 {
    public static void main(String[] args) {
        Girlfriend a=new Girlfriend();
        Scanner sc=new Scanner(System.in);
        while (true) {
            try {
                System.out.println("请输入你的女朋友的姓名:");
                String name=sc.next();
                a.setName(name);
                System.out.println("请输入女朋友的年龄:");
                String age=sc.next();
                int ag=Integer.parseInt(age);//字符串转数字!!!!!!!
                a.setAge(ag);
                System.out.println(".......成功。。。。。。。");
                break;
            } catch (NumberFormatException e) {
                System.out.println("输入数字地方输入了字符串");
            }catch (NameException | AgeException e) {
                System.out.println(e.getMessage());
            }
        }
    }
}
package a0418;

import a0418.Exception.AgeException;
import a0418.Exception.NameException;

public class Girlfriend {
    private String name;
    private int age;

    public Girlfriend() {
    }

    public Girlfriend(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        if(name.length()>3){
            throw new NameException(name+"名字有误名字长度应该不大于3");
        }
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if(age>40||age<18){
            throw new AgeException(age+"年龄有误,应该为18-40之间");
        }
        this.age = age;
    }
}

 

package a0418.Exception;

/*运行时异常:由于参数问题而导致的错误;


* 编译时异常:提醒程序员检查本地信息:
* eg:      数据库连接异常
           本地文件异常
           。。。。。。
* */
public class AgeException extends RuntimeException{
    public AgeException() {
    }

    public AgeException(String message) {
        super(message);
    }
}
package a0418.Exception;

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

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

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值