vb.netasync-awaitcatch-block

'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement


I try to reproduce logic of C# program on my VB program, all going fine except one future, VB don't allow to reproduce this construction:

try
{
    await nextButton[1].ClickAsync();
}
catch
{
    await nextButton[0].ClickAsync();
}

Of course, I can just delete Await inside catch

Try
    Await nextButton(1).ClickAsync()
Catch
          nextButton(0).ClickAsync()
End Try

But in this case I receive warning

Warning BC42358 Because this call is not awaited, execution of the current method continues before the call is completed. 

This is changing workflow of program, I need click asynchronously on nextButton(1) and only this click unsuccessful I need the same asynchronous operation click, but in previous button.

How to reproduce this logic on VB.NET?


Solution

  • Do logic in the exception handler, and keep a variable indicating whether there was an exception or not. Then use that variable to determine which nextButton.ClickAsync() you call.

    Dim success As Boolean
    Try
        ' do stuff which may raise exception
        success = True
    Catch
        success = False
    End Try
    
    If success Then
        Await nextButton(0).ClickAsync()
    Else
        Await nextButton(1).ClickAsync()
    End If
    

    If nextButton(0).ClickAsync() raises the exception you're looking for, you can still put it in the Try.