何时使用
void MyMethod() {
...
//throw new ArgumentNullException("paramName");
ThrowArgumentNullException("paramName");
...
}
void ThrowArgumentNullException(string paramName) {
throw new ArgumentNullException(paramName);
}
我读到的是,使用ThrowHelper方法(一种只穿透一个例外情况的方法),而不是直接投下should<>/em> 产生较小的附则。
这一点以及明显的cap势(另一层间接)可能是不直接投诚的良好原因,至少在某些情况下。
不管怎么说,海事组织的缺点也并非不重要。
- A part of the (exceptional) control flow is hidden
- Exceptions end up having a more cryptic stacktrace
- the compiler (2.0) will not recognize that ThrowHelper calls are exit points from a method, hence some code-around is necessary.
我的有限经验是,总体设计往往更糟。
int MyMethod(int i) {
switch (i) {
case 1:
return 1;
default:
ThrowMyException();
}
return 0; // Unreachable (but needed) code
}
This may partly be a matter of personal taste. Anyway what are your personal guidelines about this issue? Do you find it is a good idea to use ThrowHelpers for all those common tasks like method param validation (ThrowArgumentNullException(paramName) and such)? Am I missing something obvious on this issue?
Btw I m试图避免将这一问题与validation issue混为一谈,例如:
ThrowIfNameIsNullOrEmpty(name);