Reputation: 19
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
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
Reputation: 114787
Yes, this doesn't work. You'd have to fulfill two contradictory requirements:
this
call has to be the first statementthis
call has to be in a try..catch
statement.So this can't be solved.
What you could do:
y=0
FrazioneException
to a runtime exception and remove throws
.Upvotes: 2