What am I doing wrong? Java exceptions

0

Main (TesteExceptions.java:14):

Conta c1 = new ContaCorrente(444, 444);
    c1.setSaldo(5000);
    Conta c2 = new ContaCorrente(444, 445);
    c2.setSaldo(353);

    System.out.println(c1.getSaldo() + "\n" + c2.getSaldo());

    c1.transfere(c2, 1);

    System.out.println(c1.getSaldo() + "\n" + c2.getSaldo());

Method transfers (Account.java:22):

public void transfere(Conta destino, double valor){
    if (this.getSaldo() >= valor) {
        if (this != destino) {
            this.saca(valor);
            destino.deposita(valor);
        }
        throw new AccountException("you can not make transfers to your own account");
    }
}

Method out (AccountCurrent.java:25):

@Override
public void saca(double valor) {
    if (this.getSaldo() >= valor) {
        super.setSaldo(super.getSaldo() - valor - this.taxa);
    }
    throw new BalanceException("you tried to withdraw a higher amount than the balance in your account");
}

Console output:

  

5000.0  353.0Exceptioninthread"main" br.com. . .exceptions.BalanceException: you tried to withdraw a   higher amount than the balance in your account at    . .ContaCorrente.saca (ContaCorrente.java:25) at    . .Contact.transfer (Account.java:22) at    .TestExceptions.main (TestExceptions.java:14)

What am I doing wrong?

    
asked by anonymous 04.05.2018 / 17:04

1 answer

6

You are always going through your throw , whether or not you enter your if .

Put it inside else

@Override
public void saca(double valor) {
  if (this.getSaldo() >= valor) {
    super.setSaldo(super.getSaldo() - valor - this.taxa);
  }else{
    throw new BalanceException("you tried to withdraw a higher amount than the balance in your account");
  }
}

Same thing happens in your other method.

public void transfere(Conta destino, double valor){
  if (this.getSaldo() >= valor) {
    if (this != destino) {
        this.saca(valor);
        destino.deposita(valor);
    }else{
       throw new AccountException("you can not make transfers to your own account");
    }
  }
}
    
04.05.2018 / 17:14