AlexGH AlexGH - 1 month ago 11
C# Question

try catch block or boolean flag?

I'm not sure about my code, I want to save first into Blob Azure and if it was successful then save that url into my database, I have two ways to do this. The first one using a

boolean variable
named
flag
, if
flag
value is set to true then I can save it into my database, but I'm not sure if this code is the best approach. Is it possible that for some reason the file is not uploaded to
Blob
and even if that happens
flag
value is set to
true
?:
First approach using
boolean flag variable
:

using (Stream fileStream = file.InputStream)
{
blockBlob.UploadFromStream(fileStream);
flag = true;
}

if (flag == true)
{
Urls.Add(blockBlob.SnapshotQualifiedUri.ToString());
db.Save();
}


Or should be a better approach to use a
try catch
block?

try
{
using (Stream fileStream = file.InputStream)
{
blockBlob.UploadFromStream(fileStream);
}
}
catch(Exception)
{
//do something
}

Urls.Add(blockBlob.SnapshotQualifiedUri.ToString());
db.Save();


Please explain in your answer the differences between each approach, personally I think that a
try catch
should be a better approach but I want to confirm in here :)

Answer

Normally incases like this, I go a combination of the two and create a method that handles the upload and returns true or false depending on whether the upload was successful, or an exception occurred.

The try catch allows for any potential exceptions to handled appropriately, and the flag becomes simply an indicator to inform you whether the process succeeded or not.

For example, for your upload code, I would create an extension method like this:

public static bool TryUploadFile(this CloudBlockBlob blockBlob, File file)
    try
    {
       using (Stream fileStream = file.InputStream)
       {
           blockBlob.UploadFromStream(fileStream);
       }

       return true;
    }
    catch(Exception)
    {
      //do some logging or other error handling
    }

    return false;
}

And then call the method like so:

bool succeeded = blockBlob.TryUploadFile(file);

if (succeeded)
{
    Urls.Add(blockBlob.SnapshotQualifiedUri.ToString());
    db.Save();
}