I have an ASP.NET web app which is small yet has a fair amount of C# behind it.
I am trying to run some code, which is dependent on a class library/.dll I have produced (containing business logic). When I debug, after I bind to datasource property, I get an object reference not set to an instance object.
I know how to fix these errors as I have done more than my fair show when I lacked experience, but the trouble I have is I cannot find the last method to execute (which will in turn help me find the variable at fault) until this exception. Is there a way I can make the code break when it reaches the line of code causing this exception (or the line of code matching the last method called in the stacktrace)? I will probably do a find for that method signature but I don't really like this approach. Is this something for windbg?
I guess this is what they mean by unmaintainable code.
Look at the stack trace that is most likely printed out with the error.
Also try breaking on exceptions - Debug Menu -> Exceptions, Choose CLR Exceptions
VS should highlight the line from which the exception was thrown. If it doesn't, you can enable it in Debug > Exceptions. If you put a breakpoint on or before this line (or if it doesn't give you a line, on or before the code you suspect of throwing it), and then "Step In" repeatedly, you will eventually reach the code where the exception is thrown.
Related
Whenever I have a try/catch statement in my own code, the Exception still breaks to debugger.
I can turn off the check Break when this exception type is
thrown.
I don't want to do that because I do want to break in all other cases that I don't have a try/catch.
I can turn Except when thrown from this dll. I don't want to that for the exact same reason. There are valid reasons in that DLL why I want to break when I do not try/catch it myself.
I just want to not break when I have a try/catch statement, because I am already handling it so I don't want to be bugged by every external call that is failing.
How can I do this?
UPDATE
This mainly seems to be a problem with ASP.NET. Probably because there is one big try/catch per request in the outermost ASP.NET layer.
So what I'm looking for in a way is something like:
Break only try/catched in external code.
Maybe I don't understand your question but if you just take out "Break when this exception type is thrown" you should have the exact behaviour you want. The debugger will still break if the exception isn't caught. The only thing this checkbox does is tell the debugger to break even if the exception got caught.
If this is not the behaviour you want I may need some clarification to understand your question.
Edit:
Since you've now edited your question and you seem to be looking for "Break only try/catched in external code.", I can only tell you that I wouldn't know of such a feature and have never used anything like that. That does not mean it doesn't exist though.
At some point while developing my C# application, the following started to appear in the VS Output pane whenever I create an OpenFileDialog:
First-chance exception at 0x75A6C42D (KernelBase.dll) in (myapp).exe: 0x000006BA: The RPC server is unavailable.
I've been maintaining this application for years, and definitely never saw this before, so I started rolling back in SVN to determine when it began.
Bafflingly, revisions in which it occurs & doesn't occur seem to be inconsistent; if I go back sufficiently far it never happens, but there's an "area" when I can check a revision, it won't happen, I'll check another revision, it will, then I'll return to the first, and this time it suddenly will. In other words, I can't seem to reliably pinpoint when it started happening.
To illustrate this, here's an excerpt of my tests, indented for clarity. Numbers are revisions. For each test, I "update to revision" and do a full rebuild.
3977: Exception. This is the most-recent revision.
3839: OK. Since it didn't happen, I'll start working my way back up to see when it starts
3843: OK
3852: OK
3890: Exception. So it started between 3852 & 3890.
3852: Exception. Huh?? I JUST tried 3852, and last time it didn't happen!
3778: OK. Going back this far, I've never seen it happen.
3852: Exception. I guess I'll start working my way BACK to see when it stops.
3828: Exception
3810: OK
3828: Exception. Just making sure.
3810: OK. Just making sure again.
3828: OK. What?? 3828 showed the exception last time I tried!
3852: OK. (but previously it showed the exception)
3890: Exception
I'm aware that I can just tell VS not to break on these types of exceptions, and ignore them. But as mentioned, after years of working on this software, I've never seen it once - so I'd like to determine exactly when and why they started, rather than just turning a blind eye.
This has nothing to do with your project. When you use the shell dialogs, like OpenFileDialog, you load Explorer into your process. Which comes with a lot of baggage, you also get all of the shell extensions loaded. The kind that customize Explorer, they work just as well in the dialog.
Misbehaving ones are quite common. Programmers tend to use the quirkier kind. Any mishap in such a shell extension is now visible to you, the debugger tells you about it.
So, nothing actually went wrong, the exception was caught and handled. Explorer implements counter-measures against bad shell extensions destabilizing it and automatically disables them. So you just have a lame-duck shell extension that doesn't work, low odds you'd notice since it probably hasn't worked for a while.
The debugger can tell you which one is bad. Enable unmanaged debugging and tick the Thrown checkboxes in the Debug + Exception dialog. The debugger will now stop when the exception is thrown. You won't see any source code but you can look at the Call Stack debugger window for hints. It displays the name of the DLL that contain the bad code somewhere on the stack, below the Windows DLL functions. The name ought to give you a hint which one is the troublemaker. SysInternals' AutoRuns utility is excellent to disable them.
I need to create a fatal exception on demand, using C#. While I have done this unintentionally enough times, now I need to, I can't find a simple way.
It's easy enough to cause a null reference error or divide by zero etc., but I need something which will CTD without giving the option to continue.
Thanks for your help.
Don't use an exception to accomplish this, it has too many side-effects. Including not terminating the program at all, whether an unhandled exception ends the program is a CLR policy that can be changed. Both by a custom CLR host and still exposed today by the legacyUnhandledExceptionPolicy config attribute.
The most reliable way to instantly abort a program, without any events getting fired and without any cleanup (including not running finalizers) is Environment.FailFast().
IMHO I prefer a milder approach. I create a custom Exception that I call FatalException. https://learn.microsoft.com/en-us/dotnet/standard/exceptions/how-to-create-user-defined-exceptions. That way when I call methods that throw FatalException, I simply do a try-catch around the call and catch (FatalException fe). I usually re-throw as necessary to get back to parent form which also has a the final catch for the FatalException exception and then log it (I use Log4Net), show a messagebox as to the reason for the Fatal situation and call my overridden Dispose() method and exit the application gracefully. Obviously this becomes more difficult the deeper your nested calls. The extra work is worth the extra grace to me. If this becomes a standard in your application, you will understand it when you encounter it and ensure that you don't break it. I put my Custom Exceptions in a DLL library. If your code is in a library, this approach still works because the Exceptions are also in a library they can be shared by both another library and the main application. This means your library can throw a FatalException as well, although the reasons for doing so should be few a far between.
When I'm building my programs, I have a number of try-catch blocks and when they throw errors, I seem to have trouble seeing what caused the error - I've tried looking at the stack-trace but I always end up commenting out the error handling and re-running.
Is there a better way? (I'm sure there must be ...)
If every time I have to comment out the bits of my try-catch to figure out why it was throwing it seems like I should be able to look at the stack-trace or something. Sorry if it's a simple question but it should have a simple answer ...
In Visual Studio, do the follow steps:
Menu [Debug]
Option [Exceptions...]
On the right of [Common Language Runtime Exceptions], check the box under [Thrown].
Now your application will always stop (as if it is a breakpoint) at the line where an exception is thrown.
The title may be a little confusing so I'll explain. Say you had this call chain...
public DoWork(index) >> private DoWorkHelper(index) >> private CheckIndex(index)
Now if you call DoWork, it traverses the calls down to CheckIndex, adding each deeper call to the call stack.
Now if someone calls DoWork with a bad value for index, it throws the exception all the way down at CheckIndex, and currently, that's where the debugger breaks. You then have to walk back up the call stack to see the real offender was that someone passed bad data to DoWork.
Now back in the VB6 days, you could simply decorate DoWorkHelper and CheckIndex with an attribute to say 'If any exception is thrown inside me, don't highlight me, but rather my caller because they were the ones that passed me bad crap!' So in this case, the code would break inside DoWork with the call to DoWorkHeper highlighted.
There was also a setting to disable this so for deeper debugging purposes it could still be thrown at CheckIndex, the level where it actually occurred, but half the time, breaking down there tells you nothing because you don't know how you got there without walking back up the call stack.
Think of it a way to decorate your code to say when you hit an exception, auto-traverse the call stack to the point where the bad value actually tells you something useful.
Note this is similar to 'Break On All Exceptions' except you're handling this via decoration. Plus, you're not setting to break on a specific type of exception (e.g. all null reference exceptions, etc.) but rather a specific method! (or more accurately, the one that called the decorated method.)
So does C# or .NET in general have this?
Update
While I credit Dark Falcon for the answer since he directed me there, I've added a more detailed explanation about what all the attributes mean, and in what context. Check it out below.
Please see the Just My Code option. You need to decorate DoWorkHelper with DebuggerHiddenAttribute or DebuggerNonUserCodeAttribute.
Just adding what I've found to better explain so people don't have to go looking elsewhere...
There are three attributes related to this: DebuggerHidden, DebuggerStepThrough, and DebuggerNonUserCode.
Here are the rules:
When Just My Code is not checked:
DebuggerNonUserCode
This is basically ignored. Breakpoints, step-into and exceptions all work the same as if this attribute wasn't there.
DebuggerStepThrough
This respects breakpoints and will break on exceptions where they occur, but you cannot manually step into blocks marked with this attribute.
DebuggerHidden
This doesn't allow you to step in to these blocks, it ignores breakpoints, and any exceptions thrown are handled in the calling method, not where they actually occur.
When Just My Code is checked
All three attributes behave the same as if you had used DebuggerHidden above.
There's another attribute, DebuggerStepperBoundary that is pretty cool. Here's the excerpt from MSDN:
Use the DebuggerStepperBoundaryAttribute to escape from stepping through code to running code. For example, in Visual Studio 2005, encountering a DebuggerStepperBoundaryAttribute while stepping through code using the F10 key (or Step Over command) has the same effect as pressing the F5 key or using the Start Debugging command.
Hope this clears things up! Sure did for me!