user1768830
user1768830

Reputation:

Getting Java Exception subclass' getMessage() to work

I'm trying to implement my first custom RuntimeException:

public class MyException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    private boolean isFizz;
    private boolean isBuzz;
    private Widget widget;

    public class MyException(boolean isFizz, boolean isBuzz, Widget widget) {
        super();

        setIsFizz(isFizz);
        setIsBuzz(isBuzz);
        setWidget(widget);
    }

    // Getters and setters for all 3 properties...

    @Override
    public String toString() {
        System.out.println("MyException is now in string form.");
    }
}

When I go to test this out:

MyException exc = new MyException(false, true, new Widget());

System.out.println(exc.toString());
System.out.println(exc.getMessage());

I get:

MyException is now in string form.
null

So getMessage() isn't working. I would like both toString() and getMessage() to produce the same string, and I thought that Throwable#getMessage() simply returned toString().

So I ask: what's the "normal" way of overriding getMessage()? Do I literally have to just override it like toString(), like so:

@Override
public String getMessage() {
    return toString();
}

Or is there a better way? Thanks in advance.

Upvotes: 2

Views: 2640

Answers (3)

Ian Roberts
Ian Roberts

Reputation: 122414

I thought that Throwable#getMessage() simply returned toString().

You've got it the wrong way round. getMessage() returns whatever message was passed to the superclass constructor:

 public MyException(boolean isFizz, boolean isBuzz, Widget widget) {
    super("This is the message");

and the default implementation of toString() returns the exception class name followed by the message.

Upvotes: 1

Brian Roach
Brian Roach

Reputation: 76918

You haven't set a message, therefore getMessage() is most certainly going to return null.

In your constructor you're calling the no-arg constructor of RuntimeException via super() ... you would need to call super(message) (or one of the other two constructors that takes a message) and provide a message.

Upvotes: 1

iTech
iTech

Reputation: 18460

You can pass the message to your parent Exception class in the constructor, e.g.

public class MyException(boolean isFizz, boolean isBuzz, Widget widget) {     
 super("MyException is now in string form.");

}

Upvotes: 0

Related Questions