Joe Ruder
Joe Ruder

Reputation: 2194

wrap a CloudStorageAccount creation in a try:catch block

I have the following C: Console program:

namespace AS2_Folder_Monitor
{
    class Program
    {
        private static CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
            CloudConfigurationManager.GetSetting("StorageConnectionString")); //points to the azure storage account

In case there is a problem with the connection string or Azure related issue I would like a try/block here.

Obviously you can't insert a try at the top of a class like this. So, how can I handle errors?

I cannot seem to move the storageAccount down into Main either. When I try that I get '} expected'

enter image description here

Upvotes: 0

Views: 193

Answers (2)

Marcus Höglund
Marcus Höglund

Reputation: 16811

Instead of wrapping the Parse method in a try-catch section to handle connection string issues, take a look at the CloudStorageAccount class static TryParse method. It will indicate whether a connection string can be parsed or not.

Implement it like this

If(CloudStorageAccount.TryParse(CloudConfigurationManager.GetSetting("StorageConnectionString"), out storageAccount))
{
     //use the storageAccount here
}

Upvotes: 1

Pietro Nadalini
Pietro Nadalini

Reputation: 1800

The error is showing up because the term private or static can't be used inside a method.

So you can declare your CloudStorageAccount object inside the try-catch like so:

static void Main(string[] args)
{
    try
    {
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
    }
    catch (Exception)
    {                
        throw;
    }
}

Another approach can be declaring your object outside of the Main and then instantiating it in the try

private static CloudStorageAccount storageAccount;
static void Main(string[] args)
{
    try
    {
        storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
    }
    catch (Exception)
    {                
        throw;
    }
}

Upvotes: 0

Related Questions