DateTime.ToUniversalTime *Should* Throw Exceptinos.

A recent .NET Base Class Library 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 throw exceptions, 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.

One thought on “DateTime.ToUniversalTime *Should* Throw Exceptinos.”

  1. “The argument to not change a defective method because something may depend on that defect is just wrong…”

    This would seem to be self-evident, and yet the .NET team as a whole just doesn’t seem to get it. This is highly discouraging, and I am afraid it will result in .NET dying an early death.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>