我发现自己编写了一些方法,其中的代码路径永远不应该发生。这是一个简化的示例:
double Foo(double x) {
int maxInput = 100000;
double castMaxInput = (double)maxInput;
if (x < 0 || x > castMaxInput || double.IsNaN(x)) {
return double.NaN;
}
double r = 0;
for (double boundary = 1; boundary<=castMaxInput; boundary++) {
if (x <= boundary) {
r += boundary * (x + 1 - boundary);
return r;
}
else {
r += boundary;
}
}
// we should never get here.
throw new SomeException();
}
这里最有意义的异常(exception)是类似
TheAuthorOfThisMethodScrewedUpException()
因为如果我们到达 for 循环的末尾,就会发生这种情况。不幸的是,对于上述结构的方法,编译器似乎不够聪明,无法确定 for 循环之后的代码永远不会发生。所以你不能什么都没有,否则编译器会提示“并非所有代码路径都返回一个值”。是的,除了循环之前,我还可以在循环之后放入 return double.NaN
。但这会掩盖问题的根源。
我的问题是 – 是否有适当的异常(exception)情况?
最佳答案
我使用 InvalidOperationException
class为了那个原因。这意味着应用程序已经达到了它不应该处于的状态。
throw new InvalidOperationException("Invalid state.");
您也可以Debug.Assert
某事是真的,或者只是Debug.Fail
当执行到达特定点时。
Debug.Fail("This should never happen!");
但调试断言/失败在 Release模式下不起作用,仅当定义了 DEBUG
条件时。是否需要取决于您的要求。
作为@AlexD correctly points out , 还有 Trace
class与其对应的Assert
和 Fail
方法,当定义了 TRACE
条件(默认情况下在项目属性中设置构建选项卡)。
顺便回答一下标题中的问题:您可以根据需要创建自己的异常。
[Serializable]
public class TheAuthorOfThisMethodScrewedUpException : InvalidOperationException
{
private const string DefaultMessage = "The author of this method screwed up!";
public TheAuthorOfThisMethodScrewedUpException()
: this(DefaultMessage, null)
{ }
public TheAuthorOfThisMethodScrewedUpException(Exception inner)
: base(DefaultMessage, inner)
{ }
public TheAuthorOfThisMethodScrewedUpException(string message)
: this(message, null)
{ }
public TheAuthorOfThisMethodScrewedUpException(string message, Exception inner)
: base(message, inner)
{ }
protected TheAuthorOfThisMethodScrewedUpException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{ }
}
然后把它扔向人们。
throw new TheAuthorOfThisMethodScrewedUpException();
关于c# - 采用无效代码路径时抛出哪个异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21861975/