1

code of c#

void method(int a)
{
    int b = get(a);
    if ( b == 0 )
    {
        throw new NullReferenceException();
    }
}

If I throw NullReferenceException, it will generate a warning, and it is not a good way.

So if there is any exception instead of NullReferenceException ? I found the ArgumentNullException, but it is not very proper to this code, because the b is not an argument.

zxy_snow
  • 51
  • 8
  • 1
    Choice of exception is mostly personal preference - so this may not be suitable question for SO. – Alexei Levenkov Nov 18 '16 at 05:26
  • @AlexeiLevenkov if I use ArgumentNullException, then the parameter is must be "a", otherwise, it will produce another warning, but I want record b is null. – zxy_snow Nov 18 '16 at 05:32
  • Why do you want generate a Exception? I would use `bool method(int a)` and `return true` or `return false` Otherwise you can look at this article: https://msdn.microsoft.com/en-us/library/87cdya3t(v=vs.110).aspx – Essigwurst Nov 18 '16 at 05:33
  • If you feel that an exception is the right way to go, why not create your own exception class, eg, `public class GetFailureException: Exception`. You just need to override the standard constructors in your class. – John D Nov 18 '16 at 05:40
  • @JohnD, your advice is good, but I will not create my exception, because they won't sign off my code :p. I search the project code find they use ArgumentException to handle this thing. Thanks a lot! – zxy_snow Nov 18 '16 at 05:45

2 Answers2

2

As @AlexeiLevenkov said in his comment, choosing an exception type comes done to personal choice. However, there are some guidelines you should adhere to. Like you have seen, for example, not throwing NullReferenceException from code.

MSDN gives some pretty sound guidelines, as you could expect.

Concerning your actual question, I would, if a custom exception is not suitable, probably use InvalidOperationException. YMMV.

Christian.K
  • 47,778
  • 10
  • 99
  • 143
1

In this case if function get(a) is deterministic I would advice to throw ArgumentException and say what is allowed range of a.

I.e. throw new ArgumentException("Parmeter a must be ....", "a");

If function get(a) is nondeterministic (we cannot say what is acceptable range) then ApplicationException with message saying something about reason (i.e. "Operation cannot be performed because server is busy at the moment").

smartobelix
  • 748
  • 5
  • 16