Process or not process null parameters with exceptions

I remember reading some exception handling instructions that prevented checking for null parameters. The rationale for this was that if you leave the code as is, an exception (NullReferenceExcpetion) will be thrown when you try to use the parameter. The alternative explicitly checks for null and throws an ArgumentNullException.

This has the same effect, but you're right about the extra lines of code. You will never write code to handle any of the exceptions, and thus you will actually encounter them at runtime when testing, and then fix the code to stop the exceptions in the first place.

I'm not saying I agree with the leadership, but that made sense when I first read it and it still makes sense now.

Usually I check only null parameters for non-private methods only, but leave private methods to throw a NullReferenceException.

Does anyone know if there is any final / actual recommendation on this, so I can update my approach if necessary?

+7
source share
2 answers

This gives the same effect, but you're right with extra lines of code

No no. Consider:

public void TransferMoney(Account from, Account to, decimal amount) { from.Debit(amount); to.Credit(amount); } 

against

 public void TransferMoney(Account from, Account to, decimal amount) { // Ideally do them separately if (from == null || to == null) { throw new ArgumentNullException(); } from.Debit(amount); to.Credit(amount); } 

Both will fail with exceptions, but the first one will not work if a side effect is triggered first. This is bad and should be avoided whenever possible.

(Obviously, in a real scenario, this would supposedly be transactional, and there would be no real harm, but you accept my point.)

Also, if one parameter is used as an argument for another method or, even worse, saved for later use, you can end up eliminating the exception from a completely different place so that it can completely exclude - Obviously, there was an original problem .

Usually I check only null parameters only for non-private methods, but leave private methods to throw a NullReferenceException.

This seems like a pretty reasonable policy. If a private / internal method is called from some hairy code, and I am concerned that I may have mixed up the situation, I sometimes check it even then.

+12
source

With validation, you can pass the parameter name in an exception, which will simplify debugging.

 if (x == null) throw new ArgumentNullException(nameof(x)); 
0
source

All Articles