2
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?

3

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

@Micky: Yes, but in this case, OP is clearly returning a Task, which is the normal case.
Thanks. Your re-phrase of my question is more what I was asking anyway ;)
After reading the linked docs I understand it better - it is actually the await that causes the exception since the Task is in a faulted state. Makes sense now, thanks heaps @sstan
@Brett: Yes, exactly. The await keyword unwraps and throws the exception so that it behaves pretty transparently, and is even nice enough to throw the correct original exception type, rather than the more annoying AggregateException.
@Dear downvoter: I'm always willing to learn. If I said something wrong, don't be scared about leaving a comment. I won't bite :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.