I have one method that looks like this:
void throwException(string msg)
{
throw new MyException(msg);
}
Now if I write
Bernhof's answer is correct. However, if you are trying to encapsulate a large chunk of logic when instantiating your exception, then all you need to do is change your code from this:
void throwException(string msg) {
throw new MyException(msg);
}
to this:
Exception makeException(string msg) {
return new MyException(msg);
}
Then your calling code will look like this:
int foo(int x, y) {
if (y == 0) {
throw makeException("Doh!");
}
return x / y;
}
All other things being equal, prefer functional code to procedural code. It's easier to re-use and unit-test.
EDIT:
In light of Fred's sample code, this is what I would do. It's not a code contract, but it's still functional.
private int getVarID(string s_varID) {
int varID;
if(s_varID == "ILT") {
return 123;
} else if(s_varID == "TL") {
return 456;
} else if(s_varID == "FT") {
return 789;
} else if(int.TryParse(s_varID, out varID)) {
return varID;
} else {
throw makeParseError("varID must be an integer or 'ILT', 'TL' or 'FT'.");
}
}