Why can not I capture exceptions triggered by async void?

2

Why can not I catch exceptions triggered by asynchronous methods that do not return Task ?

public async void calcularPrecos()
{
    var tabelaPreco = await getTabelaPreco();
    /* Blá, blá, blá... */
}

public void iniciarCalculos()
{
    try
    {
        calcularPrecos();
        /* Blá, blá, blá... */
    }
    catch (WebException e)
    {
        /* A exceção é disparada mas não é capturada neste ponto. =( */
    }
}

The getTabelaPreco() method requires an internet connection, otherwise it throws an exception of type WebException , but I can not catch that exception in try-catch within iniciarCalculos() .

    
asked by anonymous 25.08.2016 / 04:12

1 answer

6

Not captured because the calcularPrecos() method returns nothing (void).

For the exception to be propagated, it must return Task or Task<T> .

When an exception is thrown from an asynchronous task that returns Task or Task <T> , it is captured and placed on the Task object returned.

For methods that return void , there is no Task object, so any exceptions posted can not be captured (unless you observe AppDomain.UnhandledException Event ).

Note that the exception is only thrown when the task runs. Try / catch will only catch the exception at this point.

In your example (1) , even if the calcularPrecos() method returned a Task , the try/catch block would not catch the exception because, when it occurs, execution will already have exited of this block.

So, to call the method you have to use await calcularPrecos(); or calcularPrecos().Wait();

See what the Async Return Types documentation says.

(1) See the by Gabriel Katakura.

    
25.08.2016 / 13:05