初学笔记:定义异常类及使用(例子)

问题:自定义一个异常类,当程序中输入的邮政编码不合法时抛出异常。:邮政编码必须是六位数字。定义一个customer类,该类中包括姓名,住址和邮政编码等属性,并有相应方法对属性进行赋值,在赋值时当邮政编码不合要求则抛出定义的异常类对象,并做相应处理。

package zhy;

class postCodeException extends Exception{
     
	public String reason;
	public postCodeException(String reason){
     
		this.reason=reason;
	}
	
	public String getReason(){
     
		return reason;
	}
}


class Customer{
     
	public String name,address;
	public int postCode;
	public Customer(String name,String address,int postCode) throws postCodeException{
     
		if(String.valueOf(postCode).length()!=6){
     
			throw new postCodeException("邮政编码必须为6位!");
		}
		this.name=name;
		this.address=address;
		this.postCode=postCode;
	}
	
	public String getName() {
     
		return name;
	}
	public void setName(String name) {
     
		this.name = name;
	}
	public String getAddress() {
     
		return address;
	}
	public void setAddress(String address) {
     
		this.address = address;
	}
	public int getPostCode() {
     
		return postCode;
	}
	public void setPostCode(int postCode) {
     
		this.postCode = postCode;
	}

	@Override
	public String toString() {
     
		return "Customer [name=" + name + ", address=" + address + ", postCode=" + postCode + "]";
	}
	
	
}


public class test8 {
     

	public static void main(String[] args) {
     
		try {
     
			Customer customer1=new Customer("朱厚宇", "四川", 123456);
			System.out.println(customer1.toString());
			
			Customer customer2=new Customer("许公卿", "山东", 54321);	
			System.out.println(customer2.toString());
		} catch (postCodeException e) {
     
			System.out.println(e.getReason());
		}
		
	}

}

在这里插入图片描述

你可能感兴趣的:(初学,JAVA,异常类)