私は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.");
}
ベストアンサー1
これは私にとってはうまくいっています:
private volatile bool _insideFirstChanceExceptionHandler;
// ...
AppDomain.CurrentDomain.FirstChanceException += OnFirstChanceException;
// ...
private void OnFirstChanceException(object sender, FirstChanceExceptionEventArgs args)
{
if (_insideFirstChanceExceptionHandler)
{
// Prevent recursion if an exception is thrown inside this method
return;
}
_insideFirstChanceExceptionHandler = true;
try
{
// Code which may throw an exception
}
catch
{
// You have to catch all exceptions inside this method
}
finally
{
_insideFirstChanceExceptionHandler = false;
}
}