ArgumentNullException message without parameter name

filipv picture filipv · Nov 6, 2014 · Viewed 7.3k times · Source

I am throwing ArgumentNullException in part of my code in C#. I want to catch and display the error message of my exception. But without the parameter name. I want to pass the parameter name to the exception constructor.

throw new ArgumentNullException("myParameter", errorMessageStringVariable);

If I call error.Message I get something like

errorMessageStringVariable parameter name: myParameter

I want to display only the errorMessageStringVariable. Is it possible using ArgumentNullException, without some kind of formating on the error.Message?

Answer

Jeppe Stig Nielsen picture Jeppe Stig Nielsen · Nov 6, 2014

If you want to construct the exception without the name, use:

new ArgumentNullException(null, errorMessageStringVariable)

But if you want to present an ArgumentNullException where the paramName is set, the answer seems to be no. You have to use string manipulation on the Message property.

You could create a new class that derives from ArgumentNullException.