Thiago Borges
Thiago Borges

Reputation: 1

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? he will see all my code! How can I avoid this?

Upvotes: 0

Views: 337

Answers (3)

Russ B
Russ B

Reputation: 880

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
    {
        //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.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500475

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.

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.

Upvotes: 3

JeffRSon
JeffRSon

Reputation: 11176

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. OTOH, do you know tools like reflector? Your code isn't really a secret.

Upvotes: 2

Related Questions