How to prevent exceptions bubbling up in C#?

How to prevent exceptions bubbling up in C#?

别再吹冷风 发布于 2021-11-25 字数 471 浏览 793 回复 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?

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。



需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。


没有心的人 2022-06-07 4 楼

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?

甩你一脸翔 2022-06-07 3 楼

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

说好的呢 2022-06-07 2 楼

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.

攒一口袋星星 2022-06-07 1 楼

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