简体   繁体   English

在实例化类的地方引发异常-C#

[英]Throw exception where the class was instantiated - C#

I am developing a library that will be used by programmers. 我正在开发一个供程序员使用的库。 When I am throwing an exception, the debugger goes to where the exception was thrown, and not where the class was instantiated or the method was executed. 当我引发异常时,调试器转到引发异常的位置,而不是实例化类或执行方法的位置。

With a try .. catch this can be solved, but what if the programmer who is using the library does not open a try .. catch? 使用try .. catch可以解决此问题,但是如果使用该库的程序员没有打开try .. catch怎么办? he will see all my code! 他会看到我所有的代码! How can I avoid this? 如何避免这种情况?

he will see all my code! 他会看到我所有的代码!

Well yes, if you distribute your code. 好吧,是的,如果您分发代码。 If you don't, how would you expect the code to be seen? 如果不这样做,您将如何看待代码? Don't forget that you're in a different situation to most developers using your library, as you have the source code on your machine. 不要忘记与使用库的大多数开发人员情况不同,因为您的计算机上有源代码。 Try the same DLL on a machine which doesn't have the source code. 没有源代码的计算机上尝试相同的DLL。

The developer may see a decompiled version of your code, perhaps - is that such a great problem? 开发人员可能会看到代码的反编译版本,这是一个很大的问题吗? If so, you should look at obfuscating your code - but be aware that that comes with some logistical downsides too. 如果是这样,您应该考虑使代码变得混乱-但要注意,这也带来了一些逻辑方面的缺点。

I suspect this really just isn't a problem. 我怀疑这真的不是问题。

Well, if you make a release version of your library and you don't provide debugger symbols (pdb) the debugger of the libraries user shouldn't show your code. 好吧,如果您创建了库的发行版,并且没有提供调试器符号(pdb),则库用户的调试器不应显示您的代码。 OTOH, do you know tools like reflector? OTOH,您知道反射器之类的工具吗? Your code isn't really a secret. 您的代码并不是真正的秘密。

If I understand what you are looking for I think you want to use a try catch in your code and instead of a catch block where you handle the exception you want to rethrow it like this: 如果我了解您要寻找的内容,我想您想在代码中使用try catch,而不是在要处理异常的catch块中使用以下方法将其重新抛出:

try
    {
        //exception code
    }
    catch (Exception e)
    {
         throw e;
    }

If I remember correctly, throwing like this will reset the stack trace whereas just a throw will keep the stack trace in tact. 如果我没记错的话,这样的抛出将重置堆栈跟踪,而仅仅抛出将使堆栈跟踪保持完整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM