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.
Task, which is the normal case.await that causes the exception since the Task is in a faulted state. Makes sense now, thanks heaps @sstan
asyncorawaitanywhere in those linked pages.