Search code examples
c#asynchronousexceptionmethodsthrow

Throw new Exception in asyc method


How properly throw exception in async method?

public async void Method()
{
  if(value)
    throw new Exception("Error!");
}

Solution

  • Like that, but return a Task. When you await the Task, it will throw the exception in the caller.

    public async Task DoSomethingAsync()
    {
        throw new Exception("Error!");
    }
    
    await DoSomethingAsync(); // throws
    

    You almost never want to use async void as you will not be able to wait for it to complete, get a return value or have any exceptions thrown.