I'm using the FirstChanceException
event to log details about any thrown exceptions.
static void Main(string[] args)
{
AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
Console.WriteLine("Inside first chance exception.");
};
throw new Exception("Exception thrown in main.");
}
This works as expected. But if an exception is thrown inside the event handler, a stack overflow will occur since the event will be raised recursively.
static void Main(string[] args)
{
AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
throw new Exception("Stackoverflow");
};
throw new Exception("Exception thrown in main.");
}
How do I handle exceptions that occur within the event handler?
Edit:
There's a few answers suggesting that I wrap the code inside the event handler in a try/catch block, but this doesn't work since the event is raised before the exception can be handled.
static void Main(string[] args)
{
AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
try
{
throw new Exception("Stackoverflow");
}
catch
{
}
};
throw new Exception("Exception thrown in main.");
}