簡體   English   中英

C#編譯器缺陷?:不檢測總是拋出異常的方法

[英]C# compiler flaw?: Not detecting methods that always throw exceptions

為什么MS C#編譯器在以下場景中抱怨“並非所有代碼路徑都返回值”?

public int Foo(bool flag)
{
    if(flag)
    {
        return 1;
    }
    else
    {
        ThrowException(); // this method always throws an exception

        // return -1; // why do I need to add this code that will never be called?
    }
}

謝謝!

它無法猜測ThrowException()是一個總是拋出異常的方法。 為此,您需要靜態代碼分析。

VS 2010中提供了靜態代碼分析,但我認為僅適用於更昂貴的VS版本。

else分支沒有return語句。 這意味着Foo在進入else分支時不返回值。

你為什么不這樣做:

public int Foo(bool flag)
{
    if (!flag) {
        ThrowException();
    }

    return 1;
}

順便說一下,我總覺得首先應該進行驗證。

錯誤消息說明了一切:並非所有代碼路徑都返回一個值。 我認為ThrowException()的目的是拋出異常。 如果它這樣做,我可以看到錯誤消息看起來如何奇怪。 但是,請考慮接受此有效代碼的后果。 如果ThrowException()的實現ThrowException()被更改為不再拋出異常,則上面的代碼會突然失敗,這可能會讓人大吃一驚。 編譯器正在選擇安全之路。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM