题目

自定义一个异常类,当程序输入邮政编码不合法时抛出这个异常。邮政编码必须是六个数字。

定义一个customer类,该类包括姓名、地址、邮政编码等属性,并有相应的方法对属性进行赋值,赋值时当邮政编码不合要求时抛出定义的异常对象,并作相应的处理。

package Work4;

public class customer {
	String name,addr;
	int pcode;
	void setCustomer(String name,String addr,int pcode) throws numException{
			this.name=name;
			this.addr=addr;
			this.pcode=pcode;
			String code=Integer.toString(pcode);
			if(code.length()!=6)
				throw new numException("邮政编码为六位数");
	}
	void showInfo(){
		System.out.println("name:"+name+" address:"+addr+" postcode:"+pcode);
	}
	public static void main(String[] args) {
		customer a =new customer();
		try {
			a.setCustomer("xian", "qingdao", 266000);
		}catch(numException e){
			System.out.println(e.getReason());
		}
		a.showInfo();
	}
}
package Work4;

public class numException extends Exception{
	private String reason;
	public numException(String r) {
		reason = r;
	}
	public String getReason() {
		return reason;
	}
}