2

コード例:

  public class ElementList
  {
        // some code...

        public ElementList (Element owner)
        {
              // some code...
        }

        public void Add (Element e)
        {
              if (e == owner) // cannot add child which will be self-parent
              {
                    throw new SomeException (); // main problem here
              }

              childList.Add (e);
        }
  }

では、どのような例外をスローする必要がありますか? カスタム例外を提案する場合は、適切な名前を教えてください。

4

3 に答える 3

1

これはArgumentExceptionの仕事のようです。それをサブクラス化して独自のものを作成するのが最善です-ParentElementArgumentExceptionのようなものは十分に明確な名前です-したがって、この特定の条件と一般的な引数の例外(要素以外のものを渡すなど)をテストできます。

于 2013-01-03T03:52:50.280 に答える
1

ArgumentException例外はあなたの議論によって引き起こされるので、私はお勧めしますe

if (e == owner) // cannot add child which will be self-parent
{
    throw new ArgumentException(/* Include more exception details here */);
}
于 2013-01-03T03:52:53.150 に答える
1

要するに: ArgumentExceptionトリックを行います。ただし、コードで簡単に管理できる例外をスローすることはお勧めできません。

コードを次のように書き直すことをお勧めします。

public void Add (Element e)
        {
              if (e != owner)
              {
                  // Not the owner, do your operation
                   childList.Add (e);
              }
              else {
                    // Log error message or display warning to user
                 }              
        }

ただし、例外シナリオを続行する場合、コードはおそらく次のようになります。

if (e == owner) // cannot add child which will be self-parent
{
    throw new ArgumentException("Can not add child which will be self-parent");
}

編集:参照として、もちろん、詳細な理解のためにMSDN の記事を使用できます。

于 2013-01-03T03:54:19.963 に答える