How could i catch the Exception
thrown by a DataReceivedEventHandler
?
This post is the same as mine, but for async methods instead of handlers : Catch an exception thrown by an async void method
Here's an oversimplified version of my code:
public static void Main()
{
try
{
using (Process process = CreateProcess())
{
process.Start();
process.BeginErrorReadLine();
process.WaitForExit();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message); // never goes here
}
}
private static Process CreateProcess()
{
Process process = new Process();
process.ErrorDataReceived += ActionOnErrorDataReceived;
return process;
}
private static void ActionOnErrorDataReceived(object sender, DataReceivedEventArgs e)
{
throw new Exception(e?.Data);
}