諸悪の根源

Exception クラスには、最も内側の例外(つまり発生源)の情報を取得するために、GetBaseException メソッドが用意されていたんですね。知らなかった。

ちょっと実験してみます。

using System;

namespace ExceptionSample
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                try
                {
                    try
                    {
                        // NullReferenceException を発生させる
                        string temp = null;
                        temp.GetType();
                    }
                    catch (Exception ex)
                    {
                        // 内包する
                        throw new InvalidOperationException("", ex);
                    }
                }
                catch (Exception ex)
                {
                    // さらに内包する
                    throw new ArgumentNullException("", ex);
                }
            }
            catch (Exception ex)
            {
                // NullReferenceException が出力されたら成功
                Console.WriteLine(ex.GetBaseException());
            }

            Console.ReadLine();
        }
    }
}

f:id:griefworker:20090326175456p:image

確かに諸悪の根源である NullReferenceException が取得出来ていますね。
これはデバッグに便利。