DateTime.ToUniversalTime *Should* Throw Exceptinos.

Published on Tuesday, June 12, 2007


DateTime.ToUniversalTime Should Throw Exceptinos.

A recent .NET Base ClassLibrary blog post points out that DateTime.ToUniversalTime does not throw an exception for overflow values.

This circumvents different Microsoft-sanctioned guidelines about using exceptions for exceptional situations, error reporting guidelines, not using return codes to communicate errors (which essentially what this is), the Method/TryMethod pattern, allowing the error to propagate to a level that knows how to deal with it, etc.

I would recommend having overflows handled as exceptions and the addition of a TryToUniversalTime. If the Method/TryMethod pattern is the favoured approach to providing two methods that result in the same thing–one without exceptions–this is impossible if the Method doesn't throw exceptions. i.e. you can't use Method/TryMethod pattern and therefore if you provided another method to convert to universal time that did throwexceptions,you'd be forced to implement a completely different pattern.

The argument will be that ToUniversalTime can't change because there's code that assumes it doesn't throw an exception. I would argue that this isn't a realistic case and that code that uses ToUniversalTime simply does no error checking because it can't: MinValue and MaxValue are valid values you can't use them to decide whether an error has occurred.

The argument to not change a defective method because something may depend on that defect is just wrong and is used too much as a crutch to avoid not having to deal with redesigning a proper method and dealing with the consequences.

This would apply equally to TimeZone.ToUniversalTime.

comments powered by Disqus