0

I am unable to catch the logon SqlException in C#.

This is my code:

using (SqlConnection connection = new SqlConnection(connectionString)) 
{
    try
    {
        connection.Open();
    }
    catch (SqlException) 
    { }
}

It is not even working like this:

catch (Exception) { }

This should catch ALL exceptions, but it does not. The SqlExceptions always gets thrown. This is what it says:

SqlException:
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: Cannot open database "foo" requested by the login. The login failed.

I am using the exact same try/catch when reading from the database (to catch a TimeOut) and it works perfectly fine. Also tried some variants from this question, but no luck so far.

Specs: Visual Studio 2013 Prem v12.0, .NET 4.5, Win8.1

Community
  • 1
  • 1
Philipp
  • 69
  • 1
  • 11

1 Answers1

1

Your debugger is set to break on all exceptions (or at least CLR exceptions). If you continue execution, you will hit your catch block.

I generally develop code with that setting (break on all CLR exceptions) because it turns up problems early in the development cycle. I would not change that setting.

Although you should not use Exceptions for flow control, if you run into an issue where code is often throwing an exception that you will gracefully handle during development, you can use the DebuggerStepthrough attribute to prevent the debugger from breaking in that particular method.

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553