2

How to detect the InvalidOperationException type

Here is the inner exception message:

System.InvalidOperationException: ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.

I need to detect exactly this type of exceptions to handle it. Can I know its HResult number or the exception code? or another way?

narouz
  • 195
  • 1
  • 2
  • 8

3 Answers3

1

This code may help

try
{
    //your code here...
}
catch (Exception exception) when (exception.InnerException is InvalidOperationException)
{
    var exceptionMessage = "ExecuteNonQuery requires an open and available Connection";
    if (exception.Message.Contains(exceptionMessage) || exception.InnerException.Message.Contains(exceptionMessage))
    {
        //handle it...
    }
}
0

You can use a try/catch exception handling hierarchy, so that InvalidOperationException will be caught first and handled separately from other exception types such as the generic exception type.

try
{
    // Normal workflow up here
}
catch (System.InvalidOperationException ioex)
{
    // Handle InvalidOperationException
    Console.WriteLine(ioex.StackTrace);
}
catch (System.Exception ex)
{
    // Handle generic exception
    Console.WriteLine(ex.StackTrace);
}

However, your question suggests that this will not work for you, because you mention an inner exception. In that case you probably need to do some type checking on the inner exception like this:

try
{
    // Normal workflow up here
}
catch (System.Exception ex)
{
    if (ex.InnerException is InvalidOperationException) 
    { 
        // Handle InvalidOperationException
    }
    else 
    { 
        // Handle generic exception
    } 

    Console.WriteLine(ex.StackTrace);
}
robbpriestley
  • 3,050
  • 2
  • 24
  • 36
0

Could you give us more context? It would make it easier for us to answer your question.

However, if I understand you correctly, you try to process 'something' with the inner exception. As of C# 6 there are exception filters available. For more information about exception filters see Exception filters.

The documentation also provides an example.

In your specific case, you could use the exception filter as follows:

try
{
    // Do something that could cause a InvalidOperationException
}
catch (InvalidOperationException ex) when (ex.InnerException is SomeTypeOfException)
{
    // Handle this type of exception
}
catch (InvalidOperationException ex) when (ex.InnerException is AnotherSomeTypeOfException)
{
    // Handle this kind of exception
}
Danny
  • 181
  • 7
  • 1
    Yeah, I know that, but as I know that the System.InvalidOperationException is thrown in many cases and I need to handle it in this specific case (when the message is like "ExecuteNonQuery requires an open and available Connection. The connection's current state is closed"). Also, I don't need to compare the exception message as a string. – narouz Nov 25 '19 at 08:40