class IllegaNameException extends Exception//非法姓名异常
{
public IllegaNameException(String message)
{
super(message);
}
public IllegaNameException()
{
super();
}
}
class IllegalAddressException extends Exception//非法地址异常
{
public IllegalAddressException(String message)
{
super(message);
}
public IllegalAddressException()
{
super();
}
}
class Student
{
String name;
String address;
public void setName(String name) throws IllegaNameException
{
this.name = name;
int n=name.length();
if(n<1||n>5)
{
throw new IllegaNameException("姓名长度不符合要求");
}
}
public void setAddress(String address) throws IllegalAddressException
{
this.address = address;
int n=address.length();
boolean flag=false;
for(int i=0;i<n;i++)
{
if(address.charAt(i)=='省'||address.charAt(i)=='市')
{
flag=true;
}
}
if(!flag)
{
throw new IllegalAddressException("地址长度不符合要求");
}
}
}
public class Test6_3_zxj {
// (三)自定义异常的定义、拋出和捕获试验
//
// (1)自定义两个异常类非法姓名异常IllegaNameException和非法地址异常IllegalAddressException。
//
// (2)定义Student类包含Name和Address属性,和setName、setAddress方法,当姓名长度小于1或者大于5抛出IllegaNameExceptio,当地址中不含有”省”或者“市”关键字抛出IllegalAddressException。
//
// (3)在main方法中进行捕获试验。
public static void main(String args[]) throws IllegaNameException, IllegalAddressException {
Student s=new Student();
try {
s.setName("i have 7 sons,they are my roomates");
}
catch(IllegaNameException e)
{
System.out.println("姓名输入错误");
}
try {
s.setAddress("我们生活在瓦罗兰大陆德玛西亚区");
}
catch(IllegalAddressException e)
{
System.out.println("地址输入错误");
}
}
}
自定义两个异常类非法姓名异常IllegaNameException和非法地址异常IllegalAddressException。
最新推荐文章于 2023-02-26 18:46:57 发布