When throwing exceptions, I often pass in a formatted string that exposes details about the problem that has occurred. I always specify a formatting provider if possible (which is good practice because otherwise you may forget to decide which culture is appropriate and as the default is the current culture, that can lead to many bugs).
Here's an example:
throw new InvalidOperationException(
string.Format(
CultureInfo.CurrentCulture,
"{0} is a bad number.",
number));
I'm tempted to use CurrentCulture
, as shown above, because exception messages are targeted at human beings (ofcourse, code should never act on the exception message itself). The message will be formatted using the client's culture so whenever I need to display it to my client, it looks nice.
However, besides displaying messages to users, exceptions may be logged to a log file as well. I've seen many messages sit in my log files, with all kinds of cultures used for formatting them. Pretty ugly! In this case, InvariantCulture
would be more appropriate or perhaps the culture of the server that is hosting the log file.
The point here is that when formatting an exception, you just never know your audience so it seems impossible to decide which culture to use when formatting. It would be great to be able to postpone the formatting to the point at which the exception is caught but that would go way beyond the way exceptions are implemented in .NET.
So what are your thoughts on this?