.net – Always check parameters and throw exceptions

exceptionnet

Should you always check parameters and throw exceptions in .NET when the parameters are not what you expected? E.g. null objects or empty strings?

I started doing this, but then thought that this will bloat my code a lot if it’s done on every single method. Should I check parameters for both private and public methods?

I end up throwing a lot of ArgumentNullException("name") exceptions even though the code handling the exception can’t really do anything different programmatically since there is not guarantee that "name" will not change in the future.

I assume this info is just helpful when viewing a log full of exception information?

Is it best practice to always “plain for the worst”.

Best Answer

My two cents: All your public methods should always check the validity of the parameters being passed in. This is typically called "programming by contract" and is a great way to catch errors quickly and avoid propagating them through your private functions which many would argue (including myself) shouldn't be unit tested directly. As far as throwing exceptions, if your function or program can't correct the error itself, it should throw an exception because it has been thrown into an invalid state.