简体   繁体   中英

How to catch Exception thrown by a DataReceivedEventHandler?

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);
}

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM