JAVA基础--自定义异常exception

异常图解



捕获异常有三种格式:①try-catch  语句;②try-catch-finally 语句;③try-finally 语句。

如果在try 或者 catch 中存在return 语句,这时finally语句还是会执行,且在return 语句前执行,执行后再执行return。


throws  与  throw  的区别

throws 是在方法的后面抛出异常的声明,语法:[(修饰符)](返回值类型)(方法名)([参数列表])[throws(异常类)]{......}
             public void doA(int a) throws Exception1,Exception3{......}

throw是抛出一个异常类,语法:throw (异常对象); 如自定义异常、空指针异常等。


用户自定义异常类,只要使用自定义异常类是Exception的子类即可,开发步骤为:

1.创建自定义异常类。继承Exception

2.在方法中通过throw关键字抛出异常对象。

使用自定义异常:
a)  编写如下异常类:空异常。年龄低异常、年龄高异常、身份证非法异常。
b)  编写员工类:
      i. 有编号、姓名、年龄和身份证号等属性;
      ii. 构造器1:初始化编号、姓名、年龄,如果名字为空,抛出空异常;如果年龄小于18,抛出年龄低异常;如果年龄高于60,抛出年龄高异常;
    iii. 构造器2:初始化身份证号,使用正则表达式来匹配,如果不是合法的身份证号,抛出身份证非法异常;
c)写一个测试类来验证这些异常。

import java.util.regex.Pattern;

public class Excep {	
	public static void main(String[] args) {		
		Employee em = new Employee("001", "小明", 20, "51132219941018437");		
		try {
			em.EX();
		} catch (NullException e) {
			System.out.println(e.warnMess());
		}catch(AgeLowException e){
			System.out.println(e.warnMess());
		}catch(AgeHighException e){
			System.out.println(e.warnMess());
		}catch(IdIlleagleException e){
			System.out.println(e.warnMess());
		}		
		System.out.println("111");		
	}
}
class Employee{
	String ID;
	String name;
	int age;
	String IdCard;	
	public Employee(String id,String n,int a,String ic) {		
		this.ID = id;
		this.name = n;
		this.age = a;
		this.IdCard = ic;		
	}	
	public void EX() throws NullException,AgeLowException,AgeHighException,IdIlleagleException{
		if(this.name.isEmpty()){
			throw new NullException();
		}
		if(this.age < 18){
			throw new AgeLowException();
		}
		if(this.age > 60){
			throw new AgeHighException();
		}
		boolean control = 
				Pattern.matches("\\d{17}[[0-9]*[a-z]*]{1}",this.IdCard);
		if(!control){
			throw new IdIlleagleException();
		}
	}	
}
class NullException extends Exception{	
	String message;	
	public NullException(){
		message="空异常";
	}	
	public String warnMess(){
		return message;
	}	
}

class AgeLowException extends Exception{
	String message;	
	public AgeLowException() {
		message = "年龄低异常。。。";
	}	
	public String warnMess(){
		return message;
	}
}

class AgeHighException extends Exception{
	String message;	
	public AgeHighException() {
		message = "年龄高异常。。。";
	}	
	public String warnMess(){
		return message;
	}
}

class IdIlleagleException extends Exception{
	public String message;	
	public IdIlleagleException() {
		message="身份非法异常。。。";
	}
	public String warnMess(){
		return message;
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值