0

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);
}
klev
  • 622
  • 7
  • 10
  • 1
    Is there a specific reason as to why you can't use a `try-catch` block in the event handler? This might have some useful information: https://stackoverflow.com/a/8745599/2720343 – Dortimer Dec 11 '19 at 18:29
  • i thought i was missing something, but didn't thought it was a bad practice. I will do it in another way. Thanks for the link! – klev Dec 11 '19 at 19:00

1 Answers1

0

As Dortimer made me understand thanks to his comment, to throw an exception from an event handler is a bad practice. So here's an equivalent way to achieve what i was trying to do:

bool error = false;
string errorMsg = String.Empty;

public static void Main()
{
    try
    {
        using (Process process = CreateProcess())
        {
            process.Start();
            process.BeginErrorReadLine();

            process.WaitForExit();

            if (error)
            {
                throw new Exception(errorMsg);
            }
        }   
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
}

private static Process CreateProcess()
{
    Process process = new Process();

    process.ErrorDataReceived += ActionOnErrorDataReceived;

    return process;
}

private static void ActionOnErrorDataReceived(object sender, DataReceivedEventArgs e)
{
    error = true;
    errorMsg = e?.Data;

    Process p = (sender as Process);
    if (p != null && p.HasExited == false)
    {
        p.Kill();
    }
}
klev
  • 622
  • 7
  • 10