Blue Eagle
Blue Eagle

Reputation: 55

custom exception only prints out null when called in a try/catch block

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

Upvotes: 1

Views: 1955

Answers (1)

OTM
OTM

Reputation: 654

On the PersonException constructor you are passing the message to the super class constructor and not assigning to PersonException message field and hence the field value is null. But when printing it you are getting the value of PersonException message field which prints null as expected. To correct it

  1. you should either not have message field in PersonException and use use super class getMessage() method and no need for the getter and setter in PersonException class. This is a recommended approach.
  2. Or you should assign the message to PersonException message field and use getter to retrieve it.

Upvotes: 4

Related Questions