How to treat division by 0

Asked

Viewed 1,841 times

1

I have the code where there can be a division by zero:

Binding binding = new Binding();
GroovyShell shell = new GroovyShell(binding);

conta = shell.evaluate(conta).toString();

txtConta.setText(conta);

Where in the 4th line, the method evaluate(conta).toString(); returns the result of an arithmetic expression in String. But if you have any division by 0, the program closes and launches the ArithmeticException just on that same line. Is there any way I can verify if there is any division by 0 in this section and just print on the screen a String as "Error: Split by 0" without crashing program ?

  • You can put the code inside a Try Catch block and catch when you give the Exception you launch the message treating it, Stating that there was a split by 0

  • 1

    To help: https://stackoverflow.com/a/1657925/6510304

  • Remember that this Groovyshell is a "third party" API. It returns some errors in its own classes, but the Exception released by it is the same Arithmeticexception, returning the 4th line of the example.

2 answers

5


If you cannot do the check in the innermost method, you can capture the exception and do something.

I think the best idea is to treat this in the most internal method, capture the exception should be in the last case.

Example:

try {
    conta = shell.evaluate(conta).toString();
}catch(ArithmeticException ex) {
    // Faça aqui a sua mensagem/tratamento do erro
}
  • If it were possible to intercept account would be more elegant, but not only of elegance lives the code

  • 1

    I think the API GroovyShell which throws the exception. Anyway, I also find it more interesting to treat in the more internal method.

3

You can put inside a Try catch this stretch.

try{
    conta = shell.evaluate(conta).toString();
    txtConta.setText(conta);
} catch(ArithmeticException ex){
    txtConta.setText("Não divida por zero");
}

Browser other questions tagged

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