在try:catch块中包装CloudStorageAccount创建

问题描述 投票:0回答:2

我有以下C:控制台程序:

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

如果连接字符串或Azure相关问题出现问题,我想在这里尝试/阻止。

显然你不能在这样的类顶部插入一个try。那么,我该如何处理错误呢?

我似乎无法将storageAccount移动到Main。当我尝试我得到'}期待'

enter image description here

c# azure
2个回答
0
投票

错误显示是因为术语privatestatic不能在方法中使用。

所以你可以在CloudStorageAccount中声明你的try-catch对象,如下所示:

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

另一种方法可以在Main之外声明你的对象然后在try中实例化它

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

1
投票

不要将Parse方法包装在try-catch部分中以处理连接字符串问题,而是查看CloudStorageAccount类static TryParse方法。它将指示是否可以解析连接字符串。

像这样实现它

If(CloudStorageAccount.TryParse(CloudConfigurationManager.GetSetting("StorageConnectionString"), out storageAccount))
{
     //use the storageAccount here
}
© www.soinside.com 2019 - 2024. All rights reserved.