代码之家  ›  专栏  ›  技术社区  ›  Joe Ruder

将CloudStorageAccount创建包装到尝试:抓块

  •  0
  • Joe Ruder  · 技术社区  · 7 年前

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

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

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

    那么,我该如何处理错误呢?

    我似乎也不能把storageAccount移到Main。 当我尝试时,我得到了}期望值

    enter image description here

    2 回复  |  直到 7 年前
        1
  •  0
  •   Pietro Nadalini    7 年前

    出现错误是因为 private static 不能在方法内部使用。

    所以你可以申报 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;
        }
    }
    
        2
  •  1
  •   Marcus Höglund    7 年前

    不要将Parse方法包装在try-catch节中以处理连接字符串问题,而是查看CloudStorageAccount类static TryParse

    像这样实施

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