How to deal divide by 0

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 on the 4th line, the evaluate(conta).toString(); method returns the result of an arithmetic expression in String . However if you have a division by 0, the program closes and launches the ArithmeticException just on that line. Is there a way for me to check if there is any division by 0 in this snippet and just put a String on the screen as "Error: Divide by 0" without crashing?

    
asked by anonymous 03.07.2017 / 19:29

2 answers

5

If you can not do the verification on the innermost method, you can catch the exception and do something.

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

Example:

try {
    conta = shell.evaluate(conta).toString();
}catch(ArithmeticException ex) {
    // Faça aqui a sua mensagem/tratamento do erro
}
    
03.07.2017 / 19:43
3

You can put this snippet inside a try catch.

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