Search code examples
c#try-catchgototry-catch-finally

Does GOTO in CATCH block in c# execute FINALLY?


Pretty simple question:

int retryAttempts = 3;

retry:
try {
    await getSemaphore();
    throw new Exception();
}
catch {
    if (0 > retryAttempts--) {
        await Task.Delay(5000);
        goto retry;
    }

    return;
}
finally {
    releaseSemaphore();
}

In this example, will the semaphore be released one or three times?


Solution

  • finally will execute every time you leave the catch block. So in your case releaseSemaphore() will be called three times (after each goto).

    I also invite you to read the official documentation about try-finally here