mans
mans

Reputation: 18168

exception generated inside an await block is not catched in try catch block

I have a sync function such as the following function that generate an IO error (I delete the detail to make it simple):

public override void SyncFunction()
{
   throw new IOException("test");
}

and I used it in this way:

try
{
    await Task.Run(() => this.SyncFunction());
}
catch (Exception ex)
{
    MessageBox.Show("Error:"+Environment.NewLine + ex.Message);
}

But when I run the application, the catch block doesn't get called, but I am getting a message that application crashed. What is the problem and how can I fix it?

Upvotes: 0

Views: 110

Answers (1)

i3arnon
i3arnon

Reputation: 116538

The code as you described it should handle the exception just fine.

However, the thing that would crash your application is an exception thrown inside an async void method as the exception has no Task to be stored inside.

So, my guess is that SyncFunction actually looks more like this:

public override async void SyncFunction()
{
    throw new IOException("test");
}

And when you invoke it the exception is posted to a ThreadPool thread and that crashes the application.

If that's the case, don't use async void unless in a UI event handler and make sure you handle such exceptions by registering to the AppDomain.CurrentDomain.UnhandledException event.

Upvotes: 2

Related Questions