Best way to check function parameters: Check null or try / catch

when implementing / using methods that return or work with instances of objects, what is the most elegant approach for checking function parameters?

Call Method:

someType GetSomething(object x) { if (x == null) { return; } // // Code... // } 

or better:

 someType GetSomething(object x) { if (x == null) { throw new ArgumentNullException("x"); } // // Code... // } 

Call Method:

 void SomeOtherMethod() { someType myType = GetSomething(someObject); if (someType == null) { return; } } 

or better:

 void SomeOtherMethod() { try { someType myType = GetSomething(someObject); } catch (ArgumentNullException) { } } 

When looking at similar questions, the reason not to use try / catch is performance. But IMHO try-catch just looks better :).

So which way is more "graceful"?

+7
methods c # exception-handling robustness
source share
4 answers

If passing to null invalid, throw an exception (i.e. this is an exception that should never happen).

If the null parameter is valid, return the corresponding object.

In general, accepting null parameters as bad practice is against the principle of least surprise and requires the caller to know that he is valid.

+8
source share

Regarding elegance, it is difficult to conclude Code Contracts .

 Contract.Requires(x != null); 
+4
source share

You should use exceptions only for exceptional cases. If you expect the argument to be (legal) null, you should check it - do not use exceptions for this. IMO, you should check for null on the calling site (before the call) if it makes no sense to pass null to your method.

+2
source share

In your example, GetSomthing is private. This means that you can track all callers and make sure that Null values ​​are not transmitted, for example.

  if (x != null) someType myType = GetSomthing(x) else // Initialize x or throw an InvalidOperation or return whatever is correct 

However, if it is not very personal, then you should do the same as Oded, and others said. Check if null is null and in most cases the ArguementExecption method is called.

0
source share

All Articles