views:

328

answers:

4

If I'm writing a class library, and at some point in that library I have code to catch an exception and deal with it, then I don't want anyone using my library to know that it even happened - it should be invisible from the outside world.

However, if they have "Catch Thrown Exceptions" turned on in Visual Studio (as opposed to "Catch User Unhandled Exceptions") then the exception will be visible to them.

Is there any way to avoid this?

+6  A: 

No. This is by design: as a developer, I run with "Catch Thrown Exceptions" turned on, so that I can see exceptions thrown in library code (and hopefully avoid them). The situation you're in applies equally to the .NET framework's own libraries too.

The best way would be to avoid throwing the exception in the first place. As a side benefit, you library code will be faster, since throwing an exception has a noticeable impact on performance (and should only be used in 'exceptional' circumstances).

Tim Robinson
A: 

You cannot prevent this. Someone can always attach an debuger to the process and monitor what is going on.

You could just remove the exception and provide the error handling yourself, but I would really not recommend that because it is some kind of reinventing the wheel - recreating the exception handling system.

The said applies of course only if the code throwing and the code catching the exception are far apart and quite unreleated. If they are tightly coupled, you should really check if the call can succeed and only call in this case. Always remeber that exception are intended for exceptional cases - not for normal control flow where you could check if the operation can succeed

Daniel Brückner
+2  A: 

The only way you can pull this off is if you put a [DebuggerHidden] attribute on the method that may throw the exception. Like others have pointed out, better to avoid the exception altogether, but this attribute will accomplish what you want.

BFree
Thank you - passing this on to the people at Project White so that I don't have to see an exception every time I call into UI Automation code that destroys the object being called.
Andrew Ducker
A: 

As Tim Robinson suggests there is no way to control someone viewing exceptions thrown from your library. His answer is good so I won't rehash it.

There are a couple of posts here on SO that you may find helpful when addressing (what sounds like) using exceptions as program flow control:

Catching exceptions as expected program execution flow control?
Why are .Net programmers so afraid of exceptions?

Gavin Miller