How should I deal with mistakes?

Asked

Viewed 300 times

0

Read a vector A with 12 elements. The vector must accept only the input of values that are divisible by 2 or 3. The input of values in the vector must be validated by the program and not by the user. The program must show on the screen the numbers inserted in the vector.

Note: Use error handling/exception routines.

And my code is exactly this:

        static void Main(string[] args)
    {
        string aux; // variavel auxiliar que ira receber o que o usuario digitar.
        int valor;
        int[] vetor = new int[12];

        for (int i = 0; i < 12; i++)
        {
            aux = Console.ReadLine();
            valor = int.Parse(aux);

            Console.WriteLine("Digite um valor para o vetor");

            while ((valor%2!=0) && (valor%3!=0))
            {
                Console.WriteLine("Apenas valores divisíveis por 2 e 3!");
                aux = Console.ReadLine();
                valor = int.Parse(aux);
            }
            vetor[i] = valor;
        }

        imprimeVetor(vetor);

        Console.ReadKey();
             


      }

    static void imprimeVetor(int[] vetor)
    {

        for (int i = 0; i < 12; i++)
        {

  
                Console.Write(vetor[i] + " - ");
                         
            
        }

    }

How to work with these error treatments. I have not used methods try-catch, should? I already check what is important in my while.

  • 3

    It should not, exception should be an exception in the code, the only thing that should change is to use the TryParse(). Well, there are some things that could be a little better, but nothing very important.

  • The way you say it, I would basically do this? while(!TryParse....) {mensagem de ero?}&#I hadn’t thought of that yet

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.

3 answers

5

Avoid exceptions as much as possible. Only use when it makes a lot of sense. Exception is the most poorly used feature of programming nowadays. People don’t know when to launch, let alone when to capture. Interestingly, they abuse the exception, but practically never create their own exception that would make more sense. I mean, people wear something they don’t understand and that’s why it only comes out wrong.

The only change you should make is to use the TryParse() to ensure that the data entered is valid. Otherwise I gave an organized, modernized and simplified in the code.

using static System.Console;

public class Program {
    public static void Main(string[] args) {
        var vetor = new int[12];
        var i = 0;
        while (i < 12) {
            WriteLine("Digite um valor para o vetor");
            if (int.TryParse(ReadLine(), out var valor)) {
                WriteLine("Você digitou o caractere de forma inválida. Por favor, digite apenas númeris inteiros!");
                continue;
            }
            if (valor % 2 != 0 && valor % 3 != 0) {
                WriteLine("Apenas valores divisíveis por 2 e 3!");
                continue;
            }
            vetor[i++] = valor;
        }
        imprimeVetor(vetor);
    }
    static void imprimeVetor(int[] vetor) {
        foreach (var item in vetor) Write($"{item} - ");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

This version works on C# 7, the code in Coding Ground works on C# 6, do not recommend using previous versions.

0

I ended up solving the "problem". I thought I should use a custom Exception to treat divisible numbers. In case, I used catch and Try just to make sure that the user will report only numbers. Follow the code snippet:

            Console.WriteLine("Digite um valor para o vetor");
            try
            {
                aux = Console.ReadLine();
                valor = int.Parse(aux);

            }
            catch
            {
                Console.WriteLine("Você digitou o caractere de forma inválida. Por favor, digite apenas númeris inteiros!");
                aux = Console.ReadLine();
                valor = int.Parse(aux);
            }
  • 3

    You’ve created a new problem

  • 1

    What if the user enters an incorrect value the second time? That is inside the block catch{}? As @bigown said, "You’ve created a new problem."

  • Got it! Your help has enlightened me a lot!

0

Preventing user errors does not mean you cannot have syntax errors for example.

Here was what I would do:

static void Main(string[] args)
{
    string aux; // variavel auxiliar que ira receber o que o usuario digitar.
    int valor;
    int[] vetor = new int[12];
    try{

        for (int i = 0; i < 12; i++)
        {
            aux = Console.ReadLine();
            valor = int.Parse(aux);

            Console.WriteLine("Digite um valor para o vetor");

            while ((valor%2!=0) && (valor%3!=0))
            {
                Console.WriteLine("Apenas valores divisíveis por 2 e 3!");
                aux = Console.ReadLine();
                valor = int.Parse(aux);
            }
            vetor[i] = valor;
        }
        imprimeVetor(vetor);
    }
    catch (Exception ex)
    {
        Console.WriteLine("ERRO: {0}", ex.Message);
    }
    Console.ReadKey();
    }

static void imprimeVetor(int[] vetor)
{
    try{
        for (int i = 0; i < 12; i++)
        {
                Console.Write(vetor[i] + " - ");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("ERRO: {0}", ex.Message);
    }
}
  • I understood, but I could do without Try catch in the function printed vector without problems, no? Just put the code so that the user type the number again in the first catch, then I am sure that all the data of the vector are treated and correct. Or I’ll be traveling?

  • Either I didn’t understand what you meant, or you’re really traveling... It’s one thing for you to handle the values that are going to be inserted into the array. Another thing is prevention of application blockages due to errors occurred during the execution of the same. Basically exceptions prevent errors by not allowing the application to be blocked. Regarding the processing of data for the vector you are the same responsibility of the programmer create anti-error conditions...

  • 1

    @There are no exceptions to this, in fact there is no reason to capture any exception in this code, exceptions must be exceptional, not the normal code. Exception is not a mechanism to make code more robust. In fact, the way most people use it makes the code more vulnerable because people believe that capturing an exception will not make a mistake. Most exceptions are programming errors and the correct thing is not to capture it but to fix the error. And data entry is valid, do not expect to give error. If try to validate except the situation is not exceptional.

  • @Mustache, that’s exactly what you said. However and second is explicit in the statement "Note: Use the error/exception handling routines.". This is the real reason you have inserted the exceptions. In fact they are good for debugging errors before releasing any application...

Browser other questions tagged

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