1

The task is to create an own exception class which has a constructor. It has one parameter, which is an integer. If it's zero we must call the super with the string of "This", if it's not zero we must call the super of "That". I can't figure out, how can I solve this because if I use If-Else conditional operator, than IDEA says "Call to 'super()' must be first statement in constructor body.". The code is:

public class MyException extends RuntimeException {
    public MyException(int number) {
        if(number == 0) {
            super("This");
        } else {
            super("That");
        }

    }
}
  • 6
    `super(number == 0 ? "This" : "That")`? – jonrsharpe May 10 '20 at 10:02
  • Thank you! It was a fast answer. :) Maybe can you answer how to do it with 3 if statement? For example if the number is less than 0, than write something, if the number is 0, than write something else, and if the number is greater than 0, than write something else. – Tamás Kiss May 10 '20 at 10:12
  • `super(number < 0 ? "Negative" : number == 0 ? "Zero" : "Positive")` – Andreas May 10 '20 at 10:39
  • Does this answer your question? [Why do this() and super() have to be the first statement in a constructor?](https://stackoverflow.com/questions/1168345/why-do-this-and-super-have-to-be-the-first-statement-in-a-constructor) – MC Emperor May 10 '20 at 10:45
  • Oh, I did not know that I can make a series of if statements like this. Thank you! – Tamás Kiss May 10 '20 at 11:12

1 Answers1

0

You could just create a private (static) method which just resolves your string. Or a Map:

private static final Map<Integer, String> map;
static {
    map.put(1, "This");
    map.put(2, "That");
    map.put(3, "SomethingElse");
}

public MyException(int number) {
    super(map.get(number));
}

The reason that super() must be the first statement within the constructor is probably because the language designers wanted to make sure the super constructor was run before anything else, to make sure the object was not in an inconsistent state.

But in my opinion, it is a little weird that

if (something) {
    super("This");
}
else {
    super("That");
}

is disallowed, but super(something ? "This" : "That") is not.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
  • Further to why super() has to be first, there is also the issue of instance variable initialisation, that has to happen AFTER the call to super() (since this class’s instance variables can be initialised from the superclass instance variables) but BEFORE the first subsequent statement. That gets very error-prone if you allow statements before super(). – racraman May 10 '20 at 11:51
  • @racraman Yes, but they could have designed it so that *local* variable usage were permitted, e.g. `Something(int a, int b) { int c = a + b; super(c); }`. – MC Emperor May 10 '20 at 12:47