Why doesn't your try catch catch it?

async void throws where you aren't looking.

Why doesn't your try catch catch it?

The problem

A catch that never runs.

async void LoadLevel( string name ){    var data = await Download( name );    Build( data );   // throws} try { LoadLevel( "forest" ); }catch ( Exception e ) { ShowError( e ); }

LoadLevel returns at its first await. By the time it throws, the try block is long gone.

The fix

Return a Task, then await it.

async Task hands the caller something to wait on. Awaiting it brings the exception back.

async void→can't wait, can't catch
async Task→await it, catch it

The fix in code

async Task, and await it.

async Task LoadLevel( string name ){    var data = await Download( name );    Build( data );} try { await LoadLevel( "forest" ); }catch ( Exception e ) { ShowError( e ); }

Now the catch sees the error, and the caller knows when loading is done.

Watch out

The one place async void belongs.

Event handlers have to return void. Put the try catch inside them.

Event handlers
async void, catch inside
Everything else
async Task
Fire and forget
still async Task

The rule

async means async Task.

Methods
async Task
Callers
await it
Event handlers
async void, catch inside