0

When you're coding and you encounter an error, such as the following, you receive an error at the line of code where you attempted the error.

File.ReadAllText("nonexistent_file.txt");

For reference, in Visual Studio Community this looks like this: Normal unhandled exception

However, I'm designing a NuGet package (like a DLL) and sometimes I want to throw an exception, like an ArgumentException, if the user tries to pass invalid strings to a function. However, when I code this into the NuGet and then proceed to use an invalid string, the exception takes me to the line of code in my NuGet where I threw the exception, not the line of code where I attempted the error.

For example: NuGet thrown exception

I'm curious why Visual Studio takes me to the function in the NuGet code instead of where I made the invalid call. Any idea what I'm doing wrong here?

  • Hmmm maybe try using [DebuggerStepThrough](https://stackoverflow.com/a/1424436/2791540)? Or possibly [DebuggerHidden](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.debuggerhiddenattribute?redirectedfrom=MSDN&view=net-5.0)? – John Wu May 04 '21 at 18:24
  • 1
    You have the source code of your *library* on your machine. So the debugger has no trouble showing the throw location. That's not normally the case for anybody that retrieves that library with Nuget, the debugger can't do anything but walk the stack to find a statement that it does have source for. They'll thus see the exception at the call location. Feature, not a bug. – Hans Passant May 04 '21 at 19:06

2 Answers2

1

If VisualStudio can find symbols for your dll (.pdb file) and if it can find the source code matching the symbols, and you have not turned on "Just My Code", it will do its best to jump directly to that place where the exception is thrown.

If you don't include the pdb file in your NuGet package (which you presumably don't), then what you're seeing is an effect that will only appear to you as the original developer of the NuGet package, but not to others.

Or you are referencing the Project instead of the Package, which I can't see in your question.

Lemon Sky
  • 677
  • 4
  • 10
0

Your nuget package is where the exception is thrown, so that is where the code will break and VS will jump to. If you want to break within the method that calls the method in the nuget package, you will need to handle the exception and rethrow it.

i.e.

try {
  DoSomethingInMyNugetPackage();
} catch(TheNugetException ex) {
  throw; // <<< code will now break here with the same exception, rather than inside the nuget package
}
bizzehdee
  • 20,289
  • 11
  • 46
  • 76