スローされた例外に関する詳細をログに記録するために、 FirstChanceExceptionイベントを使用しています。
static void Main(string[] args)
{
AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
Console.WriteLine("Inside first chance exception.");
};
throw new Exception("Exception thrown in main.");
}
これは期待どおりに機能します。ただし、イベント ハンドラー内で例外がスローされると、イベントが再帰的に発生するため、スタック オーバーフローが発生します。
static void Main(string[] args)
{
AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
throw new Exception("Stackoverflow");
};
throw new Exception("Exception thrown in main.");
}
イベント ハンドラー内で発生する例外を処理するにはどうすればよいですか?
編集:
イベントハンドラー内のコードをtry/catchブロックでラップすることを示唆するいくつかの回答がありますが、例外が処理される前にイベントが発生するため、これは機能しません。
static void Main(string[] args)
{
AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
try
{
throw new Exception("Stackoverflow");
}
catch
{
}
};
throw new Exception("Exception thrown in main.");
}