0

I wrote a method, that takes an array with exact length as parameter.

When user try pass an array with wrong length to the method, the method generates an ArgumentException.

Is .NET have more specific type of exception for this case, or not? And what is the better practice: tell into the exception message the reason of the exception or the way to correct it?

4
  • No, it's the right exception for a wrong argument. Why you need to pass the length to the method at all? Maybe you can share the method with us. Commented May 8, 2018 at 7:29
  • Since arrays carry a length property inherently, what's the extra parameter for? Commented May 8, 2018 at 7:31
  • @Damien_The_Unbeliever user can pass an array with any length. but if the length is not match to exact, the exception warns about it. Commented May 8, 2018 at 7:35
  • @JeroenMostert ok, you're right, sorry. Removed. Commented May 8, 2018 at 7:36

1 Answer 1

0

Is .NET have more specific type of exception for this case, or not?

No, the .Net framework does not have a more specific exception built in for your specific case.
And while you can always create your own custom exception class, I think that in most cases it's an overkill. I would say that an ArgumentException is the correct exception to throw in this situation.

And what is the better practice: tell into the exception message the reason of the exception or the way to correct it?

When throwing an exception you include in the message what's causing the exception, not how to fix it.
In this particular case, I would probably write something like this in the error message:

"<ArrayParameterName> have and invalid length. Acceptable length is <x>"

Of course, change <ArrayParameterName> to the name of the argument and <x> to the accepted length.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.