ArgumentNullException message without parameter name
Asked Answered
C

2

9

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?

Catherincatherina answered 6/11, 2014 at 8:46 Comment(2)
Are you throwing any other exception that inherits from ArgumentException?Szczecin
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.Catherincatherina
C
12

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.

Chromogenic answered 6/11, 2014 at 9:0 Comment(1)
Thank you. That's all that I needed to know.Catherincatherina
A
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.

Acromion answered 17/11, 2017 at 10:26 Comment(2)
Your first claim is simply incorrect. Try it online (C# code is encoded in URL). In my opinion the use of an empty string is dubious.Chromogenic
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.Chromogenic

© 2022 - 2024 — McMap. All rights reserved.