question

DarrylHoar-5879 avatar image
0 Votes"
DarrylHoar-5879 asked Viorel-1 edited

try with multiple catch clauses - Visual Studio 2019, C#, .NET 4 Client Profile

I have created a custom windows service in c#.
I am using a try catch around a call to a Sql Server Stored Procedure.
ie:
try
{
int rowsaffected = cmd.ExecuteNonQuery();
}

I want to catch the SqlException and trap for error -2 (command timeout) AND I want to trap for ALL other Exceptions. I want to do some special processing with the SqlException. The issue I am having is that my google returns show confusing syntax. Is it
try
{}
catch(SqlException sql_except)
{}
catch(Exception all_except)
{}

or something else?

Thanks.

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Viorel-1 avatar image
0 Votes"
Viorel-1 answered Viorel-1 edited

Check this:

 try
 {
    int rowsaffected = cmd.ExecuteNonQuery( );
    //. . .
 }
 catch( SqlException sql_exception ) when ( sql_exception.ErrorCode == -2)
 {
    // ErrorCode is -2
    // . . .
 }
 catch( Exception exception )
 {
    // any other exception, including SqlException having other error codes
    // . . .
 }

In case of older C#, try two approaches:

 try
 {
    try
    {
      int rowsaffected = cmd.ExecuteNonQuery( );
      //. . .
    }
    catch( SqlException sql_exception )
    {
      if( sql_exception.ErrorCode != -2 ) throw;
    
      // ErrorCode is 2
      // . . .
    }
 }
 catch( Exception exception )
 {
    // any other exception, including SqlException having other error codes
    // . . .
 }

or:

 try
 {
    int rowsaffected = cmd.ExecuteNonQuery( );
    //. . .
 }
 catch( Exception exception )
 {
    SqlException sql_exception = exception as SqlException;
    if( sql_exception?.ErrorCode == -2 )
  {
    // ErrorCode is -2
    // . . .
  }
  else
  {
    // any other exception, including SqlException having other error codes
    // . . .
  }
 }


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

cooldadtx avatar image
0 Votes"
cooldadtx answered

That is correct.

try
{
//Do work that may fail
} catch (SqlException e)
{
//Handle SQL-specific exceptions
} catch (Exception e)
{
//Handle any other exception
};

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.