In my programmer's experience, I have mixed error handling all the ways possible... I have created my personal style.
However, I'd like to hear what you consider to be the pro and cons of error handling at the beginning vs at the end of the method.
Handling at the beginning:
public String GenerateSomeStringData(String data, int value)
{
if (data == null)
throw new ArgumentNullException("data");
if (value <= 0)
throw new ArgumentException("value must be greater than zero");
int dataValue;
if (!int.TryParse(data, out dataValue))
throw new InvalidOperationException("data does not contain an integer");
return dataValue * 4 + value / 12;
}
Handling at the end: (the same example)
public String GenerateSomeStringData(String data, int value)
{
if (data != null)
{
if (value > 0)
{
int dataValue;
if (int.TryParse(data, out dataValue))
{
return dataValue * 4 + value / 12;
}
else
throw new InvalidOperationException("data does not contain an integer");
}
else
throw new ArgumentException("value must be greater than zero");
}
else
throw new ArgumentNullException("data");
}
What criteria do you use when deciding how to approach this? Readability, maintainability, brevity?
Validity of input should be a precondition for execution of the method - as such I would (and do) always do the error handling first.
This has the following advantages:
It is easier to parse for a human: validating preconditions first, then execution logic (which usually results in some post condition)
Clear separation of concerns between
error handling and execution logic
within your method: validation logic is not "sprinkled in" within the execution logic
As mentioned in the comments you have to differentiate between invalid input that violates a precondition and triggers an error condition (such as throwing an exception) and valid input that constitutes an edge condition (i.e. requiring some special logic to handle). The later case I would handle separately after asserting the preconditions, at the beginning of the execution logic of your method.