Doubt about exception c #

1

Because when I have the three errors, only the first one, the day one, and the month and year one, do not shoot?

if (di > 0 && di <= 31)
{
    dia = di;
}
else
{
    throw new Exception("\n"+ "El día no puede ser menor que 1 ni mayor que 31");
}
if (me > 0 && me <= 12)
{
    mes = me;
}
else
{
    throw new Exception("\n" + "El mes no puede ser menor que 1 ni mayor que 12");
}
if (an < 1992)
{
    anio = an;
}
else
{
    throw new Exception("\n" + "Debe ser mayor a 25 años para poder registrarse");
}
    
asked by Francop 24.07.2017 в 20:28
source

2 answers

3

The use of the throw new Exception command stops the execution of the code, practically the subsequent lines are omitted since the condition where you declared the exception was fulfilled.

If what you want is to show all possible messages to the user, you could rethink the logic of validations by applying the following:

string msg = "";

if (di > 0 && di <= 31){
    dia = di;
}else{
    msg = msg + "\n El día no puede ser menor que 1 ni mayor que 31";
}

if (me > 0 && me <= 12){
    mes = me;
}else{
    msg = msg + "\n El mes no puede ser menor que 1 ni mayor que 12";
}

if (an < 1992){
    anio = an;
}else{
    msg = msg + "\n Debe ser mayor a 25 años para poder registrarse";
}

if (msg.Length > 0){
    throw new Exception(msg);
}

Store the text of the possible message in a variable until all the possible conditions are evaluated, in the end the exception is thrown if there is content in the variable msg .

    
answered by 24.07.2017 в 20:58
1

To literally answer your question, you should know that when you "throw" a Exception you would for the program execution. , that is why the other instructions are not executed.

The class Exception and any of its derived classes consume a lot of resources and memory and you should be careful to use them, except in cases where it is really required and follow these tips to do it.

P.D. Blasito has given you a good example of how to avoid using excess Exception

    
answered by 24.07.2017 в 20:59