Alf
Alf

Reputation: 39

java: super must be first in a constructor

I know this has been asked before but their situation is quite different from mine.

class Derived extends Base {
    public Derived()
    {
        try {
           super();
        } catch (Exception e) {
            ....
        }
    }
}

Problem is how do I get around the problem that super has to be first - I need to wrap it in a try/except block and that won't compile.

None of the earlier answers touched into problems with try/except in relation to this issue so don't tell me this question has already been answered.

Upvotes: 2

Views: 136

Answers (2)

Łukasz Chorąży
Łukasz Chorąży

Reputation: 644

If you can- try to use composition. Make Derived have a field of type Base (instead of extending it) and wrap a call to Base's constructor in try-catch block inside of Derived's constructor

Upvotes: 2

devgianlu
devgianlu

Reputation: 1580

You simply can't do that, make the constructor throw an exception and catch it outside.

Upvotes: 5

Related Questions