Treat Arithmeticexception in another method

Asked

Viewed 813 times

5

I want to create a divide method (double a, double b) that has Try/catch to catch 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!");
    }
}
  • Can leave the return as double even public static double divide

2 answers

6

You can let the double as return in the signature and cast 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);
    }
}

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

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

I suggest reading of this answer for better clarification

  • Using this code I get the error "Constructor Minhaexcecao in class Minhaexcecao cannot be Applied to Given types"

  • 1

    @Ana complemented my answer, in addition to creating the Minhaexcecao class, you also need to create a constructor that receives a String.

3


Try to take a divisional arithmeticexception by 0 (doubled) in Java will not work. Because, java implements the standard IEEE 754 for the double type. Therefore, instead of exception, Voce has a value that represents infinity.

In short:

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;
}

Browser other questions tagged

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