How should I deal with errors?

0
  

Read a vector A with 12 elements. The vector must only accept 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 should display the numbers inserted in the vector.

     

Note: Use error / exception handling 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 try-catch methods, should I? I already check what's important in my while .

    
asked by anonymous 19.03.2017 / 22:43

3 answers

5

Avoid exceptions as much as possible. Just use it when it makes a lot of sense. Exception is the most poorly used feature of programming nowadays. People do not know when to cast, let alone when to capture. Curiously, they abuse the exception, but virtually never create an exception that would make more sense. That is, people use something they do not understand and so it only comes out wrong.

The only change you should make is to use TryParse() to ensure that the data entered is valid. Other than that I have organized, streamlined and simplified 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} - ");
        }

    }
}

See running on .NET Fiddle . And No Coding Ground . Also I put it in GitHub for future reference .

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

    
19.03.2017 / 23:26
0

I ended up solving the "problem". I thought I should use a custom exception to handle the divisible numbers. In case, I've used catch and try just to make sure the user will only report numbers. Here is 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);
            }
    
19.03.2017 / 22:53
0

The fact that you prevent user errors does not mean that you can not have syntax errors for the time being.

Here is 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);
    }
}
    
19.03.2017 / 22:55