When I start writing a method, I usually check for exceptional conditions first in the method, using If-Then-Throw blocks.
public void ReadFile(string filePath)
{
if (string.IsNullOrEmpty(filePath)
{
throw new ArgumentException(...
This style seems to be very clear and easy to understand, but it takes up more space than I think is necessary. I want to be able to handle errors and exceptional conditions in a smart way that enables whoever's reading these errors to easy take care of them while also keeping the code itself clean.
I've looked a bit at Code Contracts, which seems to me a requirement for certain conditions before and after a method's execution. That seems to be a tad bit overkill for just a null string, and I'm not sure if you can have contract clauses within the method itself, for instance, if the path is not null but no file exists at that path.
The solution I'm thinking of using is rolling my own Assert class. This class will basically turn the above If-Then-Throw into a simple one liner.
Assert.IsFalse<ArgumentException>(string.IsNullOrEmpty(filePath), "The path cannot be null or empty.");
All Assert methods would throw an exception using the exception type and the message in the last argument. The thing is that I'm not sure if this is good practice. Does it confuse what exceptions are truly for, or what Assert actually means? Would it make error-handling easier or harder?