LoginSignup
25
29

More than 5 years have passed since last update.

try ~ catch で捕捉されてない例外をUnhandledExceptionで補足する

Last updated at Posted at 2012-08-09

C#.NET で、try ~ catch で捕捉されない例外を補足したい場合、
AppDomain.UnhandledException イベントハンドラを設定しておけば、そこで捕捉してくれます。
これで try ~ catch で捕捉し忘れても、安心アンコールワットね!

Formアプリケーション、コンソールアプリケーション、両方で使えます。

サンプルコード

program.cs
/// <summary>
/// try ~ catch で捕捉されてない例外をUnhandledExceptionで捕捉するサンプル
/// </summary>
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace SampleUnhandledException
{
    class Program
    {
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            //try ~ catch で捕捉されてる例外
            try {
                throw new Exception("1");
            } catch (Exception e) {
                Console.WriteLine("Catch clause caught : " + e.Message);
            }

            //try ~ catch で捕捉されてない例外
            throw new Exception("2");
        }

        /// <summary>
        /// try ~ catch で捕捉されてない例外を処理するイベントハンドラ
        /// </summary>
        /// <param name="sender">送信者</param>
        /// <param name="args">例外オブジェクト</param>
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args)
        {
            try
            {
                Exception ex = (Exception)args.ExceptionObject;

                //エラー処理
                MessageBox.Show(GetExceptionInfoString(ex));
            }
            finally
            {
                Application.Exit(); // 明示的に終了させる必要がある
            }
        }

        /// <summary>
        /// 例外オブジェクトからデバッグに必要な情報を文字列で返す
        /// </summary>
        /// <param name="ex">例外オブジェクト</param>
        /// <returns>例外情報の文字列</returns>
        static string GetExceptionInfoString(Exception ex)
        {
            var sb = new StringBuilder();

            sb.AppendFormat("Message={0}\n", ex.Message);
            sb.AppendFormat("Source={0}\n", ex.Source);
            sb.AppendFormat("HelpLink={0}\n", ex.HelpLink);
            sb.AppendFormat("TargetSite={0}\n", ex.TargetSite.ToString());
            sb.AppendFormat("StackTrace={0}\n", ex.StackTrace);

            return sb.ToString();
        }

    }
}

実行結果

実行結果

Log4Net と組み合わせるとよさげかもしれませんね。

参考

25
29
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
29