Skip to content

Instantly share code, notes, and snippets.

@rohinomiya
Created August 2, 2012 15:12
Show Gist options
  • Save rohinomiya/3237801 to your computer and use it in GitHub Desktop.
Save rohinomiya/3237801 to your computer and use it in GitHub Desktop.
try ~ catch で捕捉されてない例外をUnhandledExceptionで補足する ref: http://qiita.com/items/c7f69713654c47f6c7cd
/// <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();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment