Treat ArithmeticException in another method

5

I want to create a split method (double a, double b) that has try / catch to get the Arithmetic Exception, returning an error message by System.out.println; as it is not in the main method, I do not know how it has to be the signature of the method, return, etc. I needed something like this:

public static ? divide(double dividendo, double divisor){
    try{
    return dividendo/divisor;
    } 
    catch(ArithmeticException e){
        System.out.println("Erro: divisão por zero!");
    }
}
    
asked by anonymous 24.08.2015 / 19:26

2 answers

3

Trying to get an ArithmeticException from divide by 0 ( with doubles ) in Java will not work. For example, java implements the IEEE 754 standard for double type. So, instead of an exception, you will have a value that represents infinity.

In summary:

This is because the 754 standard encourages programs to be more robust.

IEEE 754 defines X / 0.0 as "Infinity", - X / 0.0 as "-Infinity" and 0/0 as "NaN."

If you want to handle this case:

//throws declara que o metodo lanca excecao... forcando o programador a envolver esse método em um try-catch
public static double divide(double dividendo, double divisor) throws ArithmeticException{
    if(divisor == 0)
        throw new ArithmeticException("O divisor nao pode ser 0 !");
    return dividendo/divisor;
}
    
25.08.2015 / 15:19
7

You can leave double as a return in the signature and throw a custom exception and capture it in your main , displaying the message:

public static double divide(double dividendo, double divisor){
  if(divisor != 0){
    return dividendo/divisor;
  } 
  else {
    throw new DivisaoPorZeroException("Erro: divisão por zero!");
  }
}

You also need to create the Exception Class MinhaExcecao :

public class DivisaoPorZeroException extends RuntimeException {

    public DivisaoPorZeroException(String message) {
        super(message);
    }
}

Next, just catch the exception using try/catch in main and display the message using System.out.println()

Remembering that making exceptions is optional and should only be used if more specific exceptions need to be thrown. Always prefer to avoid that the exception happens, correcting what you can throw it, which in your case, would prevent a divisor with value 0 being informed.

I suggest reading this answer for better clarification.

    
24.08.2015 / 19:40