简体   繁体   中英

Where to catch exception in async code?

Task task = AsyncMethod();

// do other stuff

await task;

AsyncMethod() can throw exceptions. Do I put the try-catch around the method invocation, the await , or both?

To avoid the whole debate of where the exception handling should happen, I'll just slightly change your question to: where is it possible to catch exceptions thrown from the AsyncMethod method.

The answer is: where you await it.

Assuming your AsyncMethod method looks something like this:

private async Task AsyncMethod()
{
    // some code...
    throw new VerySpecificException();
}

... then you can catch the exception this way:

Task task = AsyncMethod();

// do other stuff

try
{
    await task;
}
catch(VerySpecificException e) // nice, I can use the correct exception type here.
{
    // do something with exception here.
}

Just test it, and you will see how the await keyword does all the work of unwrapping and throwing the exception from the returned Task in a way that it feels very natural to code the try-catch block.

Relevant documentation: try-catch .

Notice what the Exceptions in Async Methods section says:

To catch the exception, await the task in a try block, and catch the exception in the associated catch block.

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