Error with java exceptions

0

I'm fighting with this java code about exceptions.

What I want to do is create a method that validates if the arguments that happen are correct, but make the exception. the problem is that this leads me to add an exception in the setter, and if I add it to this, it throws me that the constructor needs exception.

public class Contribuyente 
{

private String sexo;

public Contribuyente(String sexo){
    this.setSexo(sexo);
}

public void setSexo(String sexo) 
{
        validarSexo(sexo);
        this.sexo=sexo;
}




public static boolean validarSexo(String sexo)throws Exception
{

    boolean valido=true;
    if((!"F".equals(sexo))||(!"M".equals(sexo)))
    {
        valido=false;
    }
    if (valido==false)throw new Exception("Sexo invalido");
    return true;
   }


   }

the code is longer, I only leave the part that I have problem

    
asked by Ariel Nicolas Heredia 25.05.2017 в 20:57
source

2 answers

1

For the case of a method that only validates two values, it is not so practical to use the Exception. That is, the method validateSex should return true if it is M or F and in any other case false, without exceptions. Now, if what you are trying to do is to test the use of Exceptions and its propagation, there is no problem in adding the throws Exception clause in the constructor. In practical terms this would mean that at the time of creating that object no parameter value other than what is expected will be accepted. So in your example it is necessary to add the clause in the constructor and it will be well validated.

    
answered by 25.05.2017 в 21:37
1

If the exception bothers you so throw it as RuntimeException that is not catcheable, however I do not recommend calling public methods from the constructor, because if your class is extended and they get to overwrite that method, you will have strange behavior.

    
answered by 26.05.2017 в 19:23