views:

216

answers:

3

In my localizable app I throw an ArgumentException like this:

throw ArgumentException("LocalizedParamName", "LocalizedErrorMessage");

And I catch it like this:

catch (Exception ex)
{
    Display(ex.Message);
}

I'm getting the resulting error message as:

LocalizedErrorMessage Parameter name: LocalizedParamName

The problem here is "Parameter name: ", which is in english rather than my application's language. I suppoose that string is in the language of the .NET framework. Can anyone confirm that?

One workaround is doing this:

catch (ArgumentException ex)
{
    Display((ex as Exception).Message  + "\n" + "Translated(Parameter name:)"+ ex.ParamName);
}
catch (Exception ex)
{
    Display(ex.Message);
}

Is there any other more elegant way?

+2  A: 

The message in exceptions should be for developers, not for end users. You should always attempt to catch your exceptions in such a way that you can display a meaningful error message. (No, "The program has encountered an unexpected error and will now exit" is not meaningful.) The reason why you shouldn't display the message of an exception to an end user is because the user doesn't care that the developer passed the wrong argument from function Foo() to function Bar(), let alone how it was wrong. But when you get around to fixing the bug, you'll need to know that.

So, don't worry about internationalizing your exception messages but do internationalize your messages to the user telling them what happened, what you're doing to fix it and hopefully how they can avoid the problem in the future.

Lee
+1  A: 

Got the question now- try changing the CurrentCulture- Thread.CurrentThread.CurrentCulture. You will see that the appropriate parts of the message are localised- open up the class in reflector if you want to see how it works.

You can read more about CurrentCulture here.

RichardOD
+2  A: 

You are calling the constructor ArgumentException(string message, string paramName) with a non-empty paramName.

When you do this, you get the result you see, that is your message followed by "Parameter Name: yourParamName".

The text "Parameter Name: " comes from the .NET Framework resources: the reason you are not getting a localized version is that you presumably haven't installed the relevant .NET Framework language pack(s) on your machine. You can download language packs here.

If you install the language pack(s) for the language(s) you're using, you'll get the result you expect.

Alternatively, you can use the constructor ArgumentException(string message), and build your own message including the name of the parameter.

Joe
Nice answer- I should of put the language pack on my answer.
RichardOD