Pergunta

I have created a custom-exception that i want to throw whenever a user enters a sex that is either male of female. I did this using

class sexException : Exception
{
    public override string Message
    {
        get
        {
            return "Sex can only be either MALE or FEMALE";
        }
    }
}

Now when i want to throw the exception in my main app, i will have to create an object of the exception and then check the value before throwing the exception.

Something like

    public static void AcceptInfo()
    {
        Console.Write("Enter Sex : ");
        string sex = Console.ReadLine();
        if (sex.ToUpper() != "MALE" && sex.ToUpper() != "FEMALE")
        {
            try
            {
                sexException ne = new sexException();
                throw ne;
            }
            catch (sexException e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }

My Question is; how can i create the exception in such a way that it automatically throws when the user enters invalid data without having to just check if data is invalid like FormatException on int datatype.

Foi útil?

Solução

Exceptions are generally used for exceptional circumstances. Depending on your user interface, it might actually be impossible to select something other than male or female which would mean that it would be a good time to check.

In your example of a console application, the exception feels contrived. There's no need to throw the exception as you're handling it immediately. The idea of the exception is that it should be thrown for the caller to handle and not used as part of the program flow. You could just do this

if(!sex.Equals("male", StringComparison.OrdinalIgnoreCase)
   && !sex.Equals("female", StringComparison.OrdinalIgnoreCase))
{
    Console.WriteLine("Sex can only be either MALE or FEMALE");
}

The way FormatException and other exceptions are thrown is similar to what you have done but they don't immediately handle it like you are. So, in theory, they'd do something like this

if (sex.ToUpper() != "MALE" && sex.ToUpper() != "FEMALE")
{
   throw new sexException();
}

Whatever part of the code called this method, for example, would be expected to handle that exception in a try...catch block.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top