I created my own exception and tested with a class. when I try to use it with a try/catch block, it only prints out "null" and I dont know why. Even when I put a message to print out as a parameter in the constructor 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;
}
the class 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;}
}
the class person
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 + "]";}
}
the output i get
null