Problem with Try-Catch

0

It tells me "use of the unmapped local variable" date "and it does not let me even compile.

Should I not if or if I enter the Try and run time maybe give me error?

DateTime fecha;

        try
        {
            Console.Write("Fecha de nacimiento: ");
            nacimiento = Console.ReadLine();
            fecha = Convert.ToDateTime(nacimiento);
        }
        catch (Exception)
        {

            Console.WriteLine("Error: El formato debe ser en dd/mm/aa");

        }

        Console.WriteLine(fecha);
    
asked by Edu 16.06.2018 в 00:50
source

3 answers

4

Short answer: out of scope (scope)

This works:

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("¡Saludos Hermandad de SOes!");

        DateTime fecha;

        try
        {
            Console.Write("Fecha de nacimiento: ");
            var nacimiento = Console.ReadLine();
            fecha = Convert.ToDateTime(nacimiento);
            Console.WriteLine(fecha);
        }
        catch (Exception)
        {
            Console.WriteLine("Error: El formato debe ser en dd/mm/aa");
        }       
    }
}

This also works:

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("¡Saludos Hermandad de SOes!");

        DateTime? fecha = null;

        try
        {
            Console.Write("Fecha de nacimiento: ");
            var nacimiento = Console.ReadLine();
            fecha = Convert.ToDateTime(nacimiento);

        }
        catch (Exception)
        {
            Console.WriteLine("Error: El formato debe ser en dd/mm/aa");
        }       
        Console.WriteLine(fecha);
    }
}

The reason why this works is the "null" declaration of the "date", we achieve this thanks to the character "?".

You can define it in the following way as well:

Nullable<DateTime> fecha = null;

I recommend reading about null types: link

    
answered by 16.06.2018 / 01:39
source
1

At the moment of doing DateTime fecha; you do nothing but reserve an object of type DateTime, however this does not mean making an object DateTime , for this you have to initialize it ( DateTime fecha = new DateTime(); ) or make it null ( DateTime fecha = null; ). The error message happens because in case the try fails, at no time can the variable be initialized.

    
answered by 16.06.2018 в 01:32
0

The error message:

  

"use of the unmapped local variable" date "

is because you have to initialize the variable fecha , you must initialize it:

  DateTime fecha = DateTime.MinValue;

This would be the complete code:

DateTime fecha = DateTime.MinValue;

    try
    {
        Console.Write("Fecha de nacimiento: ");
        nacimiento = Console.ReadLine();
        fecha = Convert.ToDateTime(nacimiento);
    }
    catch (Exception)
    {

        Console.WriteLine("Error: El formato debe ser en dd/mm/aa");

    }

    Console.WriteLine(fecha);
    
answered by 16.06.2018 в 01:40