Try-Catch and “Continue” - is this possible?

爱⌒轻易说出口 提交于 2019-12-07 06:27:07

问题


I have a section in my code where I am querying all SQL Server Databases on my network. I am first trying to use a SQL Login to access the SQL Server Instance but if that fails then I want to try connecting using my Windows Credentials. After that if I still can't connect then I want the code to fail and then notify the user.

So I guess what I am asking is how can I loop back from inside of a Try-Catch block to the line just above the Try-Catch block:

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;
         }

      }

回答1:


I would probably go this route:

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;    
      }
}



回答2:


You can use a for loop combined with break when you succeed:

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

You can also record whether you succeeded, etc. or increase the number of attempts or make the number of attempts configurable.




回答3:


This blog post (albeit from 2005) shows possible solutions for your problem:

Use Goto

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

Write a Wrapper

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)) ;
}


来源:https://stackoverflow.com/questions/6146248/try-catch-and-continue-is-this-possible

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!