java自定义异常

自定义异常

/*
* 自定义异常
* 在实际开发中,有时候需要些自定义异常,也就是Exception体系中没有的异常,来解决一些特殊的问题?
* 如何创建自定义异常?
* 1:创建一个类继承Exception或者RuntimeException
* 1.1:继承Exception会让我们的异常类变为编译时异常
* 1.2:继承RuntimeException会让我们的异常类变为运行时时异常
* 2:提供无参和有参的构造器
* 如何使用自定义异常?
*/


public class Test {
	
	
	public static void main(String[] args) {
		//1:创建学生对象
		Student stu = new Student();
		//2:初始化学生
		stu.setName("宝强");
		try {
			stu.setAge(2000);
		} catch (AgeException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		
		try {
			stu.setSex("人妖");
		} catch (SexException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		
		
		
	}

}

public class Student {
	
	private String name;
	private int age;
	private String sex;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) throws AgeException {
		if(age>=18 && age<=30){
			this.age = age;
		}else{
			//System.out.println("年龄不符合范围  18~30");
			//throw new Exception("年龄不符合范围  18~30");
			throw new AgeException("年龄不符合范围  18~30");
		}
		
		
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) throws SexException{
		
		if("女".equals(sex)||"男".equals(sex)){
			this.sex = sex;
		}else{
			throw new SexException("性别只能是 男 or 女");
			//throw new Exception("性别只能是 男 or 女");
			//System.out.println("性别只能是 男 or 女");
		}
		
	}
	public Student(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}
	public Student() {
		super();
		
	}
	
	

}

public class SexException extends RuntimeException {
	
	public SexException(){
		super();
	}

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

public class AgeException extends Exception {
	
	public AgeException(String message){
		super(message);
	}
	
	public AgeException(){
		super();
	}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值