我创建了自己的异常并使用类进行了测试。当我尝试将它与try / catch块一起使用时,它只打印出" null"而且我不知道为什么。即使我将消息作为构造函数PersonException()
中的参数打印出来。
public static void main(String[] args) {
try {
Person pers1= addPerson("BOBfffffffffffffffffffffffff", 666);
System.out.println(pers1.toString());
} catch (PersonException e) {
System.out.println(e.getMessage());
}
}
private static Person addPerson(String name, int age) {
Person p= null;
p= new Person(name,age);
if(name.length()>20){
throw new PersonException("ERROR!! name too long", p);
}/*if(age<1 || age>110){
throw new PersonException("ERROR!!!! invalid age", p);
}*/
return p;
}
类PersonException
public class PersonException extends IllegalArgumentException {
/**
*
*/
private static final long serialVersionUID = 1L;
private String message;
private Object object;
public PersonException(String message, Object object) {
super(message);
this.object = object;
}
public Object getObject() {return object;}
public void setObject(Object object) {this.object = object;}
public String getMessage() {return message;}
public void setMessage(String message) {this.message = message;}
}
班级人员
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public int getAge() {return age;}
public void setAge(int age) {this.age = age;}
public String toString() {return "Person [name=" + name + ", age=" + age + "]";}
}
我得到的输出
null
答案 0 :(得分:4)
在PersonException构造函数上,您将消息传递给超类构造函数,而不是分配给PersonException消息字段,因此字段值为null。但是在打印它时,您将获得PersonException消息字段的值,该字段按预期打印null。纠正它