8

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?

filipv
  • 314
  • 1
  • 3
  • 15
  • Are you throwing any other exception that inherits from `ArgumentException`? – HuorSwords Nov 06 '14 at 08:56
  • None that I know of. But to be honest, the throwing of exception and try block are several levels apart and I don't dare to say that some other code called in between doesn't throw such exception. The code that I work on is really obscure. I'm not familiar with every possible execution path that takes place within the try block. – filipv Nov 06 '14 at 09:12

2 Answers2

11

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.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
1

If you call:

new ArgumentNullException(null, errorMessageStringVariable)

The exception message will be:

Value cannot be null. Parameter name: errorMessageStringVariable

If you instead use:

new ArgumentNullException(string.Empty, errorMessageStringVariable)

you will only get the error message.

AzP
  • 1,081
  • 1
  • 16
  • 27
Ricardo Fontana
  • 4,583
  • 1
  • 21
  • 32
  • 2
    Your first claim is simply incorrect. [Try it online (C# code is encoded in URL).](https://tio.run/##NYzBCsIwEETv@Yqhpxa0P1A8iHizRVDwHOJSAulGuttakX57rEUvA/NmeE62TlxKg3hucXmJUlcZI2rVO7hgRXA2bwP80Bj9HbX1nBcL/A7AaHtYJuzA9MS@b4eOWJshhOPk6KE@cs5L2yC70qTQf2RFtQoOkSUGKm@9Vzp5pnzRlTWJ2JbWz2zmlD4) In my opinion the use of an empty string is dubious. – Jeppe Stig Nielsen Aug 27 '18 at 15:14
  • 1
    Also note that `(new ArgumentNullException()).ParamName` is a null reference, not an empty string. That shows that the `ParamName` property is meant to be `null` (not `""`) when the parameter name is omitted. – Jeppe Stig Nielsen Aug 27 '18 at 15:23