Vavaste
Vavaste

Reputation: 19

Unreported Exception/this() need to be first statement

i m writing a very simple java class and i faced a weird problem, i know there are many simple way to resolve it but now i have a doubt

public class Frazione {
    private int num;
    private int den;

    public Frazione(int x, int y) throws FrazioneException {
        if (y == 0) {
            throw new FrazioneException();
        }
        num = x;
        den = y;
    }

    /*public Frazione(int x){                   THAT'S HOW IT SHOULD BE BASED
                                                ON THE EXCERCISE BUT IT WON'T
                                                COMPILE BECAUSE THIS ISN'T THE
                                                FIRST STATEMENT
        try{
            this(x,1);
        }catch(FrazioneException e){
            System.err.print("errore: "+e);
        }
    }*/
    /*public Frazione(int x){
            this(x,1);                         IF I TRY THIS WAY I'LL BE IN
                                               AN UNREPORTED EXCEPTION PROBLEM
    }*/
    public int getNum() {
        return num;
    }

    public int getDen() {
        return den;
    }
}

there's a way to use try and catch with this() statement?

Upvotes: 0

Views: 59

Answers (2)

prkandel
prkandel

Reputation: 26

If there are multiple constructors and you are using this keyword within a constructor to call another constructor, the invocation of another constructor (this()) must be the first line of the constructor.

Upvotes: 0

Andreas Dolk
Andreas Dolk

Reputation: 114787

Yes, this doesn't work. You'd have to fulfill two contradictory requirements:

  1. the this call has to be the first statement
  2. the this call has to be in a try..catch statement.

So this can't be solved.

What you could do:

  • If you want to throw a checked exception in the constructor, throw it also in the other one. But that doesn't make real sense, because it will never been thrown, because you never pass y=0
  • Convert FrazioneException to a runtime exception and remove throws.
  • Try to solve your requirement without throwing an exception from the constructor (I usually avoid that because it often causes too much trouble. Like the one you have)

Upvotes: 2

Related Questions