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.