In Try - Catch how the line of error can be found - vb.net

We are using visual studio. In case of try & catch we cant locate exactly the line of code for which error is thrown. Where as if we use resume, exact line is shown & we can make corrections there & test. Some times in testing environment reproducing error may not be possible in many cases. When error is thrown we have to atleast locate the error there itself. Further if procedure is a big one like having more than 400 lines then locating error without line of error is a big headache. When try catch is considered superior to on error statement, why is this feature not available? While we were using vb6 we could just type resume & check the error line. In vb.net we are searching for that feature.

Try this:
Go to the Debug menu.
Click on the the Exceptions... choice.
The following dialog should appear:
Note the Common Language Runtime Exceptions checkbox is checked.
Upon clicking OK, now when you debug your code anytime an exception is thrown by your code or the .NET Framework, the debugger will halt on the line that threw the exception. This makes finding where something is "breaking" much easier.

In VB6 the Err object is rather primitive, and gives you basic information about an error - a number and a message. "Error" state was easy to dismiss (On Error Resume Next) and proper error handling would obscure any method's intent.
.NET exceptions are more sophisticated. They're special objects that can actually contain every single bit of available information that's needed to locate an error - including the specific line of code that caused it.
That's because exceptions bubble up until they're caught (in a catch) block, and if they're not, they are unhandled and cause the program to stop. The exception will contain not only the type of error with a description and the very line of code that has thrown it, but also every single call that led to it - doing that in VB6 would require tremendous amount of meticulous "stack trace" building that could easily start lying, and wouldn't give you exact line numbers. .NET stack traces never lie.
To view the stack trace, you can place a breakpoint in any catch block and look at the exception's properties.
You can't resume like you would in VB6, because there could be dozens of method calls between the line that threw the exception and the line that catches it. But, like in VB6, you can move the yellow "current instruction" marker to another line and resume execution and re-run the try block line-by-line (F10) to see what's going wrong.

Related

Jetbrains Rider doesn't allow debugging on 3rd party exceptions

I'm not sure if I'm missing something here, but it doesn't appear to be possible to debug exceptions in Jetbrains Rider.
I have an incredibly simple piece of code that throws an exception (invalid file name) and there is no way I can find to
a) stop on the exception line in my code raising the exception, and
b) view the value of any variables in my source code that may have contributed to the exception.
I've recorded a sample video here that shows the debug attempt, and why it seems illogically impossible.
Has anyone found a way of debugging this stuff? Is Rider actually broken?
Sample video showing (attempted) debug session
For anyone experiencing the same situation, enable "Any Exception" and disable "Only break on exceptions thrown from user code" in Breakpoint Options.
You can also (as #mu88 mentions) disable debugging of external sources, but that simply reduces the clutter in stack frames.

Prevent code break in try-catch block using vb.net in Visual Studio 2019

Try-catch block don't work as expected. In Java, if I wrote something similar and an exception occur in the "Try" code, the program executes the "catch" code.
Now, let's do an example:
try
'I want to read an integer from file
FileGet(aFile, anInteger)
Catch ex as Exception
'If there is an error, i show a console message
Console.writeLine("Exception")
End Try
If I run this code (it's an example... I've this problem with every try-catch), I get a "System.IO.EndOfStreamException" and the program stop itself in the try code. I can go in the catch block with f5 or f11 (I'm using Visual Studio 2019), but I suppose the exception shouldn't be raised.
Now, I suppose that the problem is in my Visual Studio "Exception Settings": I've the default settings and I checked "Common Language Runtime Exception". Is there a way to avoid code breaking when an exception occurrs in a try-catch block?
I've also read this answer on a similar question, but it can't solve my problem because I can't find the User-unhandled exceptions checkbox. Also this similar question doesn't solve my problem.

vb.net Run on crash

My program runs for about 10 hours during the night, sometimes I wake up to see that it has crashed (for whatever reason). It is usually a "Program Name" has stopped working, and the only button there is to close the program. I have tried watching and waiting for it to crash but the problem seems very hard to reproduce (and I can't watch it 24/7). I have used try and catch statements in my program in potentially problematic areas and told the program to dump to a text file if it catches an exception. But this isn't good enough it seems.
TLDR: Is it possible to tell my program to run a particular function when an exception has been detected in the program in general (without specifics) so that I can dump the stacktrace to a text file and investigate later?
Is it possible to tell my program to run a particular function when an exception has been detected...
Yes, but the specifics depend on the platform that you are using:
If you have a Console application, put a big Try ... Catch around Sub Main.
If you use WPF, add an event handler to AppDomain's or Dispatcher's UnhandledException event. Specifics can be found in the following question:
WPF global exception handler
In you use WinForms, you can also wrap Sub Main (which might be auto-generated) or attach to AppDomain.UnhandledException, see here for details:
WinForms Global Exception Handling?
For completeness, global exception handling in web applications is done in global.asax's Application_Error method:
How to catch unhandled exceptions in an asp.net application?
It's generally not a good idea to do this. You could, however, look at AppDomain.UnhandledException. This is pretty much restricted to one domain, and you'll also receive (potentially) notifications for all unhandled exceptions unrelated to your program.
This is usually used for class libraries, but I think with a bit of fiddle, you might get it to work.

Visual Studio throwing spurious exceptions when running a program in debug

I'm working on a VB.Net program in debug in Visual Studio 2010 (10.0.40219.1) (Windows XP 5.1 2600.xpsp-sp3-gdr.120821-1629), and have noticed that while debugging it runs very slowly. When run as an executable (even the debug executable) it bowls along at a splendid speed.
The cause appears to be that the development environment is generating large numbers of exceptions (appearing in the immediate window).
A first chance exception of type 'System.ArgumentNullException
occurred in Microsoft.VisualBasic.dll
Does anyone know what the cause of this might be? It doesn't appear to have any adverse effect on the running of the program, other than to take a long time to get to the bit I'm trying to find the bug in. The exception doesn't appear to be related to any particular patch of code, and indeed it doesn't happen for most other projects.
I found an answer to a similar question for you:
A first chance exception
I would pay specific attention to the suggestion by Marcus Andren:
If you want to pinpoint where the exceptions are occurring, you can
select the Debug->Exceptions menu item, and in the dialog that
appears, check the first checkbox for "Common Language Runtime
Exceptions". This will make the debugger break as soon as an exception
occurs instead of only breaking on unhandled exceptions.
This is also one reason why it is generally a bad idea to catch
generic exceptions unless you are clearly logging the information
caught.

How to refactor VB6 code to prevent run-time errors

A VB6 app is experiencing a run-time errors at a variety of places.
I know this is the result of poor error handling, but is it possible to analyse the code to see where it is susceptible to run-time errors?
Any application is susceptible to run-time errors where there is no error handling around calls to external resources, so you could identify those points as a start.
I've used a free-tool (many years ago) that could retro-fit error handling to VB6 code, which would at least log errors and the point that they occurred.
Here it is: The HuntErr Addin for easy error handling in VB6
You need to make sure that every one of the methods (functions, subs, properties...) in your code base has an error handling statement. It's probably true that not every single one can generate a run time error, but that will protect the application from crashing without a lot of upfront analysis.
Make sure there's a statement before any executable line of code that says "On Error GoTo..." with a label, and then make sure to put that label with some error handling code at the bottom of the method. I've used a free tool called MZ-Tools 3.0 that allows you to automate the inclusion of this text. There is an Error Handler tab in the options that lets use specify what text you want to put in and where. This is what mine looks like:
On Error GoTo l{PROCEDURE_NAME}_Error
{PROCEDURE_BODY}
Exit {PROCEDURE_TYPE}
l{PROCEDURE_NAME}_Error:
LogError "{MODULE_NAME}", "{PROCEDURE_NAME}", Err, Err.Description
Then I just make sure that the LogError function exists and writes the error out to a log file that I can review.
Common sources of run-time errors in VB6 apps include
Accessing a key in a collection that doesn't exist
Calling a method or property on an object that is nothing
Using CLng to convert a string to a number when the string is null
Accessing an array beyond its length (like after calling Split and then assuming that the string has the number of pieces you expected)
So besides doing what others have suggested and analyzing where the actual errors are coming from, you could start by looking for areas such as these in your code and putting appropriate error handling around them. Keep in mind that often the best "error handling" doesn't involve using On Error at all, but preventing the error ahead of time by checking for these boundary case, like
If Not Object Is Nothing
If Len(string) > 0
If UBound(array) > x
etc...
There are some good answers here with both the On Error GoTo recommendations and the common errors that fall through the cracks that bwarner mentions.
But maybe widen the scope and utilize built-in tools to analyze code like breakpoints, watch expressions, and especially good for debugging run-time errors, the locals window (often overlooked in debugging, but very powerful) and the call stack. You can get a lot of great info on that from here: Debugging Your Code and Handling Errors
Other things to think about that may be helpful:
Invest in a tool that will help you
with the analysis like CodeSMART
2009 for VB6 or VB Project
Analyzer.
Try to port the existing application
to VB.NET - not to actually port and
use, but to view the conversion log
for things that need to be fixed.
Following Ryan's answer and the comment in response, you don't have to put error handling in every routine, just every Event and Sub Main() (and API callbacks if they don't already have it).
API callbacks refer to routines called directly by the Win32API, most often passed to Declared functions using AddressOf. (I.e. search your code for AddressOf and ensure all routines mentioned as arguments have error handlers that catch errors and do not allow them to attempt to bubble up.)
And I've just noticed this doesn't really answer the original question asked (although given the comment in response to Ryan's answer it is a good first step): Once you have error handling in every Event, etc, you will catch all errors, but you won't be able to directly analyse where all errors occur. You will need to extend the error logging to at least all the routines called by the events that log errors to more accurately locate the exact source of each error.
In VB6 a Runtime error occurs exactly when an Event function is called without error handling. So at least all your event handling functions (like Form.Open()) should be surrounded by an error handler (yes, I know VB6 does not have them), which can nicely be implemented like this (We do it in all our applications like this):
Use this as the first line of EVERY event handling function (it is a large valid label which sets the On Error at the end):
¦¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯: On Error GoTo ErrorHandler:
Now use this on the end of all those functions:
¦____________________________________________________________________________________________________________________________________: Exit Sub
ErrorHandler: handleError CodeDb, "Form_frm_filter_deletecolum", "cmd_deletecolum_Click", err.Number, err.description, err.Source, err.LastDllError, err.Helpfile, err.HelpContext, Erl: err.Clear
But replace the two strings with the module name and function name. AND replace each On Error Goto 0 with On Error Goto ErrorHandler.
Now create a function handleError with the given arguments (in my app it automatically sends a bug report into our bugtracking system), and display a nice error message.
We even pushed this a bit further, by having a prebuilt process that adds similar lines to all other (means non-event functions, or functions just called by other functions), to remember the line in which the error occured and to accumulate a complete stack trace (Yeah, stacktraces in VB6!). In addition this process adds line numbers to each line so they are given in the Erl part of the error handler.
Our tool is written as some MS Access modules, so I can't simply provide it for you, but you see where you have to go for it.