Exception handling with recursive async / await

Consider the following code:

void TopLevelCaller() {
    RecursiveAwaiter();
}

async Task RecursiveAwaiter() {
    var result = await ReceiveDataAsync();
    FireEvent(result);
    RecursiveAwaiter();
}

      

Let's assume a ReceiveDataAsync

failure is out of the question. Is it possible to modify the code to catch this exception in TopLevelCaller()

so that all error handling is done in the class where it TopLevelCaller()

exists?

It would be better if the developer handled the error like this:

void TopLevelCaller() {
    try {
        RecursiveAwaiter();
    } catch (Exception e)
    {
        // Something went wrong. Handle appropriately.
    }
}

      

than having something like:

async Task RecursiveAwaiter() {
    try {
        var result = await ReceiveDataAsync();
        FireEvent(result);
        RecursiveAwaiter();
    } catch (Exception e) {
        FireExceptionEvent(e);
    }
}

      

+3


source to share


1 answer


async void TopLevelCaller()

      

Async void is almost always a bad idea. It is for WPF management events. It's a fire and forget feature, so you won't be able to catch the exceptions TopLevelCaller throws. It should work:



async Task TopLevelCaller() {
    try {
        await RecursiveAwaiter();
    } catch (Exception e)
    {
        // Something went wrong. Handle appropriately.
    }
}

      

+1


source







All Articles