![](/img/trans.png)
[英]Why does throwing 2 exceptions in a row not generate an unreachable code warning?
[英]Throwing temporary exceptions without "unreachable code detected"
在編寫代碼時,我經常會臨時注入隨機異常以確保錯誤流符合預期。
例如
public void SomeFunc()
{
Console.WriteLine("Some code");
throw new Exception("BOOOOM!"); //added temporarily
Console.WriteLine("Some more code");
}
問題是我將警告設置為錯誤,因此編譯將失敗並檢測到 CS0162 Unreachable code ,因為“更多代碼”將永遠不會運行。
因此,只需添加您說的條件:
public void SomeFunc()
{
Console.WriteLine("Some code");
if (true)
throw new Exception("BOOOOM!"); //added temporarily
Console.WriteLine("Some more code");
}
但是不,這個編譯器足夠聰明,可以注意到條件將始終為真,並再次標記 CS0162。
我通常會得到以下結果:
public void SomeFunc()
{
Console.WriteLine("Some code");
var debug = true;
if (debug)
throw new Exception("BOOOOM!"); //added temporarily
Console.WriteLine("Some more code");
}
所以我的閑置問題是,因為我很懶,是否有更簡單的方法來欺騙編譯器? 一個班輪將是完美的。
(是的,我最終會編寫單元測試;)
這是一個雙線。 Resharper 建議並為我做了這個。 否則記住它幾乎是不可能的。
throw new Exception("Boo!");
#pragma warning disable 162
// The unreachable code is here
#pragma warning restore 162
雖然這是一個直接的答案,但我可能不會那樣做,因為它很笨重。
您還可以更改錯誤的嚴重性,以便在編譯時顯示警告。 這是我的默認設置。
具體如何執行此操作因 Visual Studio 版本而異。 這是文檔。
在 Visual Studio 2019 中,您將在 .editorconfig 文件中添加或修改它:
[*.cs]
# CS0162: Unreachable code detected
dotnet_diagnostic.CS0162.severity = warning
事實上,編譯器相當愚蠢。 它通常不識別非常量表達式。 這意味着您只需要創建一個始終為真的條件,至少有一個非常量表達式。
我相信在閱讀鏈接后,您可以想出很多這些。 這是一個例子:
if ("a".Length == 1) throw new Exception("...");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.