Andrew Ducker
Andrew Ducker

Reputation: 5490

How to prevent exceptions bubbling up in C#?

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?

Upvotes: 1

Views: 3457

Answers (4)

Gavin Miller
Gavin Miller

Reputation: 43815

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?

Upvotes: 0

BFree
BFree

Reputation: 103742

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.

Upvotes: 2

Daniel Brückner
Daniel Brückner

Reputation: 59645

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

Upvotes: 0

Tim Robinson
Tim Robinson

Reputation: 54724

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).

Upvotes: 7

Related Questions