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;
}
}
Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System. exit() it will execute always.
If an exception is thrown inside the catch-block and that exception is not caught, the catch-block is interrupted just like the try-block would have been. When the catch block is finished the program continues with any statements following the catch block.
As I mentioned above, a single try block can have any number of catch blocks. 2. A generic catch block can handle all the exceptions. Whether it is ArrayIndexOutOfBoundsException or ArithmeticException or NullPointerException or any other type of exception, this handles all of them.
So, try... catch can only handle errors that occur in valid code. Such errors are called “runtime errors” or, sometimes, “exceptions”.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With