Bug in exception handling?

B

ben

I have a custom exception

class MyException: System.Runtime.InteropServices.COMException
{
.....
}

and code like this
try
{
.....
}
catch(MyException ex)
{
//Some code
}
catch(Exception ex)
{
// Other code
}

I put a break point in the MyException catch block, and another one in
the Exception catch block. I am running into a situation where the
debugger stops in the Exception catch block with out ever stopping in
the MyException catch. I check the type of the exception in the Locals
window only to find that it's of type MyException. I'm pretty sure that
it's supposed to be caught in the first catch not the second. What
could be going wrong?
 
J

Jon Skeet [C# MVP]

I have a custom exception

I put a break point in the MyException catch block, and another one in
the Exception catch block. I am running into a situation where the
debugger stops in the Exception catch block with out ever stopping in
the MyException catch. I check the type of the exception in the Locals
window only to find that it's of type MyException. I'm pretty sure that
it's supposed to be caught in the first catch not the second. What
could be going wrong?

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

It may just be a debugger issue, of course - that's more likely than it
failing when running in release mode.
 
G

Guest

You might want to try catching COMException. Because your custom exception
extends COMException, the COMException handler should catch your exception.

Also, just FYI, it is generally recommended that custom exceptions extend
ApplicationException as documented in the ApplicationException documentation
and elsewhere on MSDN.

HTH
 
B

Barry Kelly

Dale said:
Also, just FYI, it is generally recommended that custom exceptions extend
ApplicationException as documented in the ApplicationException documentation
and elsewhere on MSDN.

This recommendation has been rescinded! Check section 7.3.2 of the
Framework Design Guidelines book, for example, or here:

http://blogs.msdn.com/brada/archive/2005/03/27/402801.aspx

The rationale in the book is from Jeffrey Richter. To paraphrase, the
idea behind ApplicationException was to separate CLR exceptions from
your own exceptions. However, CLR exceptions such as
TargetInvocationException is derived from ApplicationException, so the
class has lost its meaning and raison d'etre.

-- Barry
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top