简体   繁体   中英

Throwing out of range exception for DateTime

I have a quick question. I am not sure what is the best way of going about this. Should I throw an out of range exception for DateTime? Because I want to make my code as idiot proof as possible.

At the bottom is my code. Is this a good way of throwing the exception? When i don't throw an out of range exception a argumentexception happens. Should i throw an argument exception instead? Are these correct parameters to put in my exception. What's the best way of going about this? Is this a good way to throw exceptions in general?

Thanks

private DateTime date;
public SimpleDate(int day, int month, int year)
{
    if (day > 31 || day < 0)
    {
        throw new ArgumentOutOfRangeException("day");
    }
    if (month > 12 || month < 0)
    {
        throw new ArgumentOutOfRangeException("month");
    }
    if (year > 2100 || year < 1900)
    {
        throw new ArgumentOutOfRangeException("year");
    }
    date = new DateTime(year, month, day);
}

This is a good approach from a conceptual standpoint; your object is in the best position to know what's valid input, not your object's caller. However, obviously your logic is not complete; there are some significant "corner cases" like February 31st. It's also a duplication of work.

The DateTime constructor accepting Year, Month and Day will validate that the combination of these numbers yields a valid date, and will throw its own ArgumentOutOfRange exception if it isn't. That validation is much more complete; not only will it validate the correct number of days in each month, it will do leap year calculations as well to determine whether February 29th is valid for the specified year. Best of all, it already exists ; As Equalsk said in his comment, why reinvent the wheel?

So, the overwhelming majority of your validation should come from simply trying to construct a new Date from the entered numbers, and letting the DateTime constructor throw out as needed. You can add your own more restrictive validation on top of that as you please; for instance, restricting the entered year to between 1900 and 2100 (System.DateTime is capable of handling any four-digit year in the "common era", 0001 to 9999).

I don't see anything wrong with throwing an exception, it is generally a good idea to validate your data that is being inputted.

One thing I did notice, shouldn't

if (month > 12 || month < 0) be if (month > 12 || month <= 0) . 0 wouldn't be a valid month. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM