0

Here is my code. I have a method that deletes an Azure Block Blob. I have a try / finally block to log the failure with details, but otherwise to carry on.

I am returning a bool to identify if the item was deleted or not.

Visual Studio is telling me that the return statement at the end of the method is unreachable.

public bool Delete(string referenceId)
{
    var client = GetBlobClient();
    var container = client.GetContainerReference("qwerty");
    var blob = container.GetBlockBlobReference(referenceId);
    try
    {
        blob.Delete();
        return true;
    }
    finally
    {
        Trace.TraceWarning("Delete Blob failed: {0}", referenceId);
    }
    return false;  // <-- THIS LINE.
}

enter image description here

Why is that? Don't I have to return some value in this method.

Your insight is appreciated.

Glenn Ferrie
  • 10,290
  • 3
  • 42
  • 73

2 Answers2

5

You have no catch, so if there's an exception in your try it will just be thrown. Your method either succeeds and returns true, or an exception is thrown.

If you add a catch block, the warning will go away because that path is now accessible.

You should be able to swallow the exception (if that's what you want) by simply adding catch {} before the finally.

Looking at your code more closely, you likely want to replace the finally with a catch anyways- it's unlikely you wish to log that the delete had failed no matter the outcome.

Jonathon Chase
  • 9,396
  • 21
  • 39
  • I originally removed the `catch` to try to identify what sort of exception I'd get if the delete failed ... and I never replaced it. Thanks for the quick response. – Glenn Ferrie Aug 15 '19 at 01:25
2

The code is unreachable because of the return statement that you have in your try block, which will always execute unless an exception is thrown.

If the Delete() method of the blob variable executes seamlessly then the return statement in the try block will be executed and the method will exit (after the finally block has run) without executing any further instruction after the try/finally block. Otherwise, if it throws an exception, then the exception itself will propagate to the caller method (again, after the finally block has run) and neither return statement will be executed. In either case, the return statement at the end of the method will never be reached.

If you however delete the return statement inside the try block, you will verify that the code still successfully compiles and the return statement at the end of the method is reachable.

Cheers.