What am I doing wrong? Java exceptions

Asked

Viewed 77 times

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());

Transfer method (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");
    }
}

Bag method (Contacorrente.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: inserir a descrição da imagem aqui

5000.0 353.0 Exception in thread "main" br.com...exceptions.Balanceexception: you tried to Withdraw a Higher amount than the balance in your Account at br with....Contacorrente.saca(Contacorrente.java:25) at br with....Account.transfere(Account.java:22) at br with....Testeexceptions.main(Testeexceptions.java:14)

What am I doing wrong?

  • This exception is not java. Provide a [mcve] so that it is possible to verify the problem.

  • 1

    Alias, it seems a business rule, not a mistake.

  • 1

    In my conception you are launching an exception where you should use another mechanism. But I have given up making people understand this. https://answall.com/q/21767/101 Not to mention using double for monetary value.

1 answer

6


You’re always going through your throw, whether or not entering your if.

Put him inside the 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");
    }
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.