为什么以下代码行没有创建编译器警告?
void Main()
{
throw new Exception();
throw new Exception();
}
Run Code Online (Sandbox Code Playgroud)
在我看来,编译器应通知您无法达到第二次抛出异常.
C#编译器似乎并不关心我是否在throw语句后面有一个return语句,即使throw它很明显无法访问.相反的情况并非如此:编译器可以检测到a return之后throw无法访问.这是编译器缺陷吗?
编译好:
string MyProperty
{
get
{
return "";
throw new InvalidOperationException();
}
}
string MyMethod()
{
return "";
throw new InvalidOperationException();
}
Run Code Online (Sandbox Code Playgroud)
这不会编译,失败的return声明:
string MyOtherProperty
{
get
{
throw new InvalidOperationException();
return "";
}
}
string MyOtherMethod()
{
throw new InvalidOperationException();
return "";
}
Run Code Online (Sandbox Code Playgroud)
编辑:这是使用.NET 4.5.1,C#版本5.0.
编辑2:这是我在编译第二个选项时看到的警告(在返回之前抛出): Unreachable code detected