Try-Catch和“继续” - 这可能吗?

时间:2011-05-26 23:29:20

标签: c# .net try-catch

我的代码中有一个部分,我在网络上查询所有SQL Server数据库。我首先尝试使用SQL登录来访问SQL Server实例,但如果失败,那么我想尝试使用我的Windows凭据进行连接。之后,如果我仍然无法连接,那么我希望代码失败,然后通知用户。

所以我猜我要问的是如何从Try-Catch块内部循环回到Try-Catch块上方的行:

String conxString = @"Data Source=SQLInstance1;User ID=FOO;Password=BAR;";
bool secondTime = false;

using (SqlConnection sqlConx = new SqlConnection(conxString))
     {
         Try{
               sqlConx.Open();
               DataTable tblDatabases = sqlConx.GetSchema("Databases");
               sqlConx.Close();
               secondTime = false;
               Console.WriteLine("SQL Server found!");
         }
         Catch(System.Data.SqlClient.SqlException e){
                if (!secondTime){
                   secondTime = true;
                   conxString = @"Data Source=SQLInstance1; Integrated Security=True;";
                      //Loop back to the using statement to try again with Windows Creds
                {
                 else{
                   Console.WriteLine("SQL Server not found or credentials refused");
                 }
                   //Report Failure to connect to user

         }
         finally{
            //Reset Variable
            secondTime = false;
         }

      }

3 个答案:

答案 0 :(得分:11)

我可能会走这条路:

String conxString = @"Data Source=Instance1;User ID=FOO;Password=BAR;";
//in your main function
if(!TryConnect(conxString))
{
   Console.WriteLine("SQL Creditials failed.  Trying with windows credentials...");
   conxString = "new conn string";
   TryConnect(conxString);
}
..............
//new function outside of your main function
private bool TryConnect(string connString)
{
   using (SqlConnection sqlConx = new SqlConnection(conxString))
     {
         Try{
               sqlConx.Open();
               DataTable tblDatabases = sqlConx.GetSchema("Databases");
               sqlConx.Close();
         }
         Catch(System.Data.SqlClient.SqlException e){
                return false;
         }
         return true;    
      }
}

答案 1 :(得分:5)

成功后,您可以使用for循环与break结合使用:

for (int attempt = 1; attempt <= 2; attempt++)
{
    try
    {
        /* perform attempt */
        var success = TryToConnect();
        if (success)
            break;
    }
    catch (Exception e)
    {
        /* report error */
    }
}

您还可以记录您是否成功等,或者增加尝试次数或使尝试次数可配置。

答案 2 :(得分:-1)

blog post(尽管从2005年开始)显示了您的问题的可能解决方案:

使用转到

TryLabel:
try
{
    downloadMgr.DownLoadFile("file:///server/file", "c:\\file");
    Console.WriteLine("File successfully downloaded");
}
catch (NetworkException ex)
{
    if (ex.OkToRetry)
        goto TryLabel;
}

写一个包装器

public static bool Wrapper(DownloadManager downloadMgr)
{
    try
    {
        downloadMgr.DownLoadFile("file:///server/file", "c:\\file");
        return true;
    }

    catch (NetworkException ex)
    {
        Console.WriteLine("Failed to download file: {0}", ex.Message);
        return (!ex.OkToRetry);
    } 
}

static void Main(string[] args)
{
    while (!Wrapper(downloadMgr)) ;
}