Tutorial :Odd Try/Catch Behavior



Question:

I have a simple try/catch block

try  {       // Open the connection       _connection.Open(); // [1]  }  catch( OracleException ex ) // [2]  {       // Handle the exception       int x = ex.ErrorCode;  }  

The catch is never executed and the runtime reports 'OracleException was unhandled' at [1] which just makes my head spin. Clearly, I have a catch statement for the associated exception type. I've even tried the fully qualified type, Oracle.DataAccess.Client.OracleException at [2] and still the exception is unhandled.

The only way I can actually get the catch to work is by catching System.Exception at [2]. What is causing this odd behavior?


Solution:1

Are you dynamically loading assemblies at all, possibly using Assembly.LoadFrom or something similar? If so, you might be hitting a situation where the type that you have mutiple types loaded into different load contexts.

Assemblies loaded into different context present the same types with different identities so they do not match type equality checks etc.

From MSDN

  • The load context contains assemblies found by probing: in the GAC, in a host assembly store if the runtime is hosted, or in the ApplicationBase and PrivateBinPath of the application domain. Most overloads of the Load method load assemblies into this context.

  • The load-from context contains assemblies for which the user provided a path not included in the directories searched by probing. LoadFrom, CreateInstanceFrom, and ExecuteAssembly are examples of methods that load by path.

Of course this is just a guess, so I might be wrong.


Solution:2

Maybe it is throwing an Oracle.DataAccess.Client.OracleException instead of an Oracle.DataAccess.Client.OracleException . I know it sounds odd, but it is possible to have two types with exactly the same name loaded into a given AppDomain.

Try this...

try   {        // Open the connection        _connection.Open(); // [1]   }   catch( Exception ex ) // [2]   {        if (ex.GetType() == typeof(OracleException)) Debug.WriteLine("is match");       else Debug.WriteLine ("is not match");         // Handle the exception        int x = ex.ErrorCode;   }   

Another possibility is that the exception is wrapped. You may be getting an InvalidOperationException that contains a OracleException.

Finally, the error may just be just after your try block. Either you misread the stack trace or the line numbers in the stack trace are wrong. Both happen to me all the time.


Solution:3

You may want to catch the more general DbException.

try  {       // Open the connection       _connection.Open(); // [1]  }  catch( DbException ex ) // [2]  {       // Handle the exception       int x = ex.ErrorCode;  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »