Unhandled Exception error line and source function - vb.net

I am using VS2012 VB.net.
Can I please have some help in creating some code to calculate the error line of an exception and also the function that the exception occurred in.
Here is my current code:
Partial Friend Class MyApplication
Public exceptionListOfExceptionsToNotPauseOn As New List(Of ApplicationServices.UnhandledExceptionEventArgs)
Private Sub MyApplication_UnhandledException(sender As Object, e As ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
Dim msgboxResult As MsgBoxResult
Dim booleanExceptionFoundInList As Boolean = False
'Dim trace As System.Diagnostics.StackTrace = New System.Diagnostics.StackTrace(ex, True)
'Dim exceptionLineNumber = trace.GetFrame(0).GetFileLineNumber()
For x = 0 To exceptionListOfExceptionsToNotPauseOn.Count - 1
If exceptionListOfExceptionsToNotPauseOn(x).Exception.Message = e.Exception.Message Then
booleanExceptionFoundInList = True
End If
Next
If Not booleanExceptionFoundInList Then
msgboxResult = MessageBox.Show("An exception error has occured." & vbCrLf & "Error message: " & e.Exception.Message & vbCrLf & "Do you wish to pause on this exception again?", "Exception", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
If msgboxResult = Microsoft.VisualBasic.MsgBoxResult.No Then
exceptionListOfExceptionsToNotPauseOn.Add(e)
End If
End If
e.ExitApplication = False
End Sub
End Class
UPDATE
The code for the trace code uses an Exception data type where as the code for handling unHandled exceptions above has a parameter of "e As ApplicationServices.UnhandledExceptionEventArgs". Can I use the trace code with this data type? Do I need to cast it to an exception type? Or is it not possible?

I am not mastering in Vb.Net but previously i used below code, may be it can help you
[ex.StackTrace()]
Try
'Your Code goes here
Catch ex As Exception
MsgBox(ex.StackTrace())
End Try

Here are a couple of tips. First is to use PostSharp its a AOP kit that will let you trace all methods entry and exit using Attributes. This would direct you to the function straight away.
Another trick. Subscribing to the ThreadExceptionEventHandler actually does cause the debugger to break on unhandled exceptions! Hence temporarily comment out your MyApplication_UnhandledException and add a ThreadExceptionEventHandler
<STAThread> _
Public Shared Sub Main(args As String())
Try
'your program entry point
Application.ThreadException += New ThreadExceptionEventHandler(Application_ThreadException)
'manage also these exceptions
Catch ex As Exception
End Try
End Sub
Private Sub Application_ThreadException(sender As Object, e As ThreadExceptionEventArgs)
ProcessException(e.Exception)
End Sub
Another trick is is not to run under the debugger. The debugger is masking the exception for some reason. If you run your app normally (Ctrl+F5), you'll get the usual Unhandled exception has occurred in your application... Continue/Quit? dialog.
The code for handling unHandled exceptions above has a parameter of "e
As ApplicationServices.UnhandledExceptionEventArgs". Can I use the
trace code with this data type?
No.
You cannot easily use your trace code datatype with the UnhandledExceptionEventArgs. One idea might be to make a class that inherits from UnhandledExceptionEventArgs but I don't know how you'd call the MyApplication_UnhandledException function with the special type, because that function is invoked when an Exception is Unhandled.

Related

Throwing exception from sub to async call

This is a windows forms application in which I have a particular form. On this form I display the progress of some processing that is supposed to happen in the background asynchronously. All of it works great, except for when I try to handle exceptions that are caught within the background processing....
This is the sub in my form's code that calls the Async function, which is in a module containing all the background processing code:
Public Async Sub BasicProcessing()
Try
Dim processTarget As Action(Of Integer)
processTarget = AddressOf UpdatePulseProcessing
myProgress = New Progress(Of Integer)(processTarget)
myCount.Vehicles = Await ProcessmyCountFile(myCount, myProgress)
If OperationCanceledByUser = True Then
Exit Sub
End If
Catch ex As Exception
MessageBox.Show(Me, "Unable to update count." _
& Environment.NewLine & ex.Message, _
"Error updating count", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End Try
End Sub
This is the async function that it calls, which is in a separate module:
Public Function ProcessmyCountFile(CountToProcess As Count, ByVal ProgressObject As IProgress(Of Integer)) As Task(Of List(Of Vehicle))
myProgressObject = ProgressObject
basicToken = New CancellationTokenSource
Try
Return CType(Task(Of List(Of Vehicle)).Run(Function()
If basicToken.IsCancellationRequested Then
Return Nothing
Exit Function
End If
myCountFile = CountToProcess
MyVehicles = New List(Of Vehicle)
'All that is important in here to note is a call to a regular sub within this module
CreateVehicles()
Return MyVehicles
End Function, basicToken.Token), Global.System.Threading.Tasks.Task(Of List(Of Global.STARneXt.Vehicle)))
Catch ex As Exception
Throw New Exception(ex.Message)
Return Nothing
End Try
End Function
Public Sub StopProcess()
If Not basicToken Is Nothing Then
basicToken.Cancel() ' We tell our token to cancel
End If
End Sub
This is the regular sub called by the Async function:
Private Sub CreateVehicles()
Try
'In here are calls to other regular subs within the same module, let's just call them A and B
Catch ex As Exception
StopProcess()
Throw New Exception("Error creating vehicles at pulse " & pulsePointer & ". " & ex.Message)
End Try
End Sub
When I run this code with data that I know ends up generating an error in sub B, the error does propagate up, as far as up to the method that is directly called by the async function....
So when running in VS, it will stop at "Throw New Exception("Error creating vehicles at pulse " & pulsePointer & ". " & ex.Message)", with the Message containing the message thrown by sub B.
This is what the debugger says on that line:
An exception of type 'System.Exception' occurred in MyProject.exe but
was not handled in user code. Additional information: Error creating
vehicles at pulse....[error message propagated up as thrown by called
subs]. Arithmetic operation resulted in an overflow.
Then strangely enough, within the debugger if I hit "Step Into", it does then return to the sub in my form that called the Async function, which shows the message box on the GUI.
So how do I get this to automatically return back up to the original form code to show the message box? Why does it stop where it stops without continuing to propagate?
FYI, I did find this question, but it ultimately did not help.
#StephenCleary was right - I created a new install for my project as it is, and in the installed version I do get the message box with the expected error message.
Strange behavior on the part of the debugger, and a bit discouraging, but none-the-less I am glad that my code as laid out in my question does actually work.

vb.net - error handling on main method or every method

I have a program that is interacting with emails. I am upgrading it from vb6 to vb.net. There was extensive error handling in the program before ,using On Error commands, to ensure that it never broke, just ignored and logged the errors. In most functions there is this On Error code, where it handles an error in the function by returning a default value and exiting the function. For Example:
Public Function Init() As Boolean
On Error GoTo Err_Init
Init = True
Exit_Init:
Exit Function
Err_Init:
Init = False
Resume Exit_Init
End Function
I want to change all error handling to Try - Catch blocks. My initial thought when I was upgrading the vb6 code was to replace all error handling with a simple Try - Catch around the Sub Main entry point, as below:
Public Sub Main()
Try
Init()
catch
'do stuff
end try
End Sub
public function Init() As boolean
init = true
end function
as any errors in the program would be caught in this way and I could handle them all in one Try - Catch.
However I then realised that, that would not make the function above return a value of False when an error occurred. If I still want this functionality do I have to wrap everything in Try blocks?
Since your concern is that you do not want the application to crash or break, Yes you can use Try cache block for that concern.
However, If you are talking about error handling in the whole application, then I would suggest that you think of a way to refactor the whole code.
Remove all the "On Error" statements and apply some new logic to handle the errors.
That logic could vary (Only logging, Retrying strategy Design pattern, etc) Think of all the expected errors and handle them accordingly.
If you need to do something special for errors in a particular function, then the function should have its own Try/Catch block to implement that behavior. For example:
Public Function Init() As Boolean
Try
'Presumably some other code goes here
Return True
Catch ex As Exception
Return False
End Try
End Function
Get rid of all the on Error steps and do the error handling globally
In the main_load put the three block below
' Get your application's application domain for error handling.
Dim currentDomain As AppDomain = AppDomain.CurrentDomain
' Define a handler for unhandled exceptions.
AddHandler currentDomain.UnhandledException, AddressOf MYExnHandler
' Define a handler for unhandled exceptions for threads behind forms.
AddHandler Application.ThreadException, AddressOf MYThreadHandler
and then add the two sub routines shown below
Private Sub MYExnHandler(ByVal sender As Object,
ByVal e As UnhandledExceptionEventArgs)
Dim EX As Exception
EX = e.ExceptionObject
If EX.StackTrace.Contains("SOMETHING") Then
My.Computer.FileSystem.WriteAllText(LogToWrite, "Error SOMETHING caught:" & EX.StackTrace & vbCrLf, True, System.Text.Encoding.Default)
MsgBox("error caught. Contact **XXX** for assistance!" & vbCrLf & vbCrLf & "Error: " & vbCrLf & EX.StackTrace,, "Fatal Error")
End If
End Sub
Private Sub MYThreadHandler(ByVal sender As Object,
ByVal e As Threading.ThreadExceptionEventArgs)
If e.Exception.StackTrace.Contains("SOMETHING") Then
My.Computer.FileSystem.WriteAllText(LogToWrite, "Error SOETHING caught:" & e.Exception.StackTrace & vbCrLf, True, System.Text.Encoding.Default)
MsgBox("Error caught. Contact **xxx** for assistance!" & vbCrLf & vbCrLf & "Error: " & vbCrLf & e.Exception.StackTrace,, "Fatal Error")
End If
End Sub
You can just check the content of the errors and respond accordingly to every single error with a Case Array..

vb.net timer and exception (try... catch) and memory leak

Scenario:
I've hundreds of applications instances running on client machines doing a certain job. Something like a cloud app.
Objective: When an error occur in any of them i want to report the error to an error-log database an quit silently the app to avoid user annoyance.
The problem:
I've migrate to VB.NET recently and don't know yet wich is the best aproach to error handle the code. Those instances are runing a routine under a timer.
Private Sub timerLifeSignal_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerLifeSignal.Tick
MAINSUB()
End Sub
Friend Sub MAINSUB()
frmSAN.timerLifeSignal.Enabled = False
...
'do the job
...
frmSAN.timerLifeSignal.Enabled = True
end sub
At first glance i've put try/catch into every single function but it leads to a memory leak since, AFIK, the exception object created was not disposed correctly.
So is there a way to make try/catch do not memory leak under these circumstances?
Thx,
UPDATE:
Basically what i was doing is something like:
Private Sub timerLifeSignal_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerLifeSignal.Tick
MAINSUB()
End Sub
Friend Sub MAINSUB()
Try
frmSAN.timerLifeSignal.Enabled = False
...
'do the job
...
frmSAN.timerLifeSignal.Enabled = True
Catch ex as Exception : gERRFUNC(" | MAIN | " & ex.Message) : End Try
end sub
friend sub dothejob
try
...
' really do the job
...
Catch ex as Exception : gERRFUNC(" | MAIN | " & ex.Message) : End Try
end sub
and so on... and finally (may here it's my mistake) another try/catch nested into here:
Public Sub gERRFUNC(Optional ByVal errorMSG As String = "")
Try
' log message on database
SQL = "INSERT INTO sanerrorlog VALUES (NULL, '" & currentMySQLTime() & "', '" & errorMSG & "');"
' function that open conn and execute the sql... working fine
' NOTE THAT INSIDE THE DORS FUNCTION THERE'S ALSO A TRY/CATCH USING THE SAME EX OBJECT.
DORS(SQL)
' clean up things
SQL = "DELETE FROM sannie WHERE sid=" & gMyID
DORS(SQL)
For i = 0 To UBound(gCONN)
If gCONN(i).State = ConnectionState.Open Then gCONN(i).Close()
Next
frmSAN.nfi.Visible = False
gWWB = Nothing
End
Catch E As Exception: End: End Try
End Sub
So... if i do this:
Private Sub timerLifeSignal_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerLifeSignal.Tick
Try
MAINSUB()
Catch ex as Exception : gERRFUNC(" | MAIN | " & ex.Message) : End Try
End Sub
Means all exceptions inside mainsub should be catched?
You have another way..
You can attach events to the app domain and main thread, in case it fails, to catch the errors.
Something like:
AppDomain.CurrentDomain.UnhandledException +=
CurrentDomain_UnhandledException;
Application.ThreadException +=
Application_ThreadException;
Application.ApplicationExit += Application_ApplicationExit;
with this in mind, every time an exception occurs, anywhere that it hasn't a catch by itself, will fall trough any of this ones...
Try/Catches by themselves don't cause memory leaks. Not finalizing something after a failure, which triggers a catch can however. By removing your try/catches, you've apparently exposed something else that does finalize, even though informally, the object which was causing a memory leak.
Ask yourself this, how could a directive in your code cause a memory leak? Try, nor Catch are references to an object, and thus could not cause memory consumption issue by themselves -- only by the logical path of the code they control.
Just for reference the memory leak problem occurs because of nested try/catch loops wich (by my mistake) uses the same variable as exception object.
To be more clear take the following example:
Public Sub gERRFUNC(Optional ByVal errorMSG As String = "")
Try
// do something wrong here
Catch E As Exception: gERRFUNC(ex.Message): End Try
End Sub
friend Sub gERRFUNC(msg as string)
Try
// call another external sub (wich eventually may also throw an execption)
// take note that the var 'E' is also referenced here and everywhere
// so as 'E' is set it enters on a Exception loop causing the 'memory leak' problem.
Catch E as Exception: End: End Try
End Sub
By removing the nested try/catch or by using a well structured error 'flow' may avoid these type of problem.
Best Regards,
Paulo Bueno.

Getting stack trace information from a dynamically loaded

My goal here is to get stack trace information from a dynamically loaded assembly. If the dynamically loaded assembly just throws the error back to the caller, the stack trace information doesn’t tell you the location in the dynamic assembly where the error occurred. If I throw my own exception, passing in the original exception, it will get added as an inner exception and will have the information need. I’m trying to avoid changing all my dynamic assemblies to throw new exceptions. Does anybody know a better way to get the stack trace information from a dynamically loaded assembly?
Public Class ErrorPlugin
' Example Function from plug in DLL
Public Function SimpleExample() As Double
Dim RentedUnits As Double = 42
Dim NumberUnits As Double = 0
Try
' Just need to generate exception
Return RentedUnits \ NumberUnits
Catch ex As Exception
' Give's me no Stack Trace infomation.
'Throw
' This will give me Stack Trace infomation,
' but requires adjusting all the plugins.
Throw New Exception("Stop dividing by zero.", ex)
End Try
End Function
End Class
Imports System.Reflection
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim rpt As Object
Dim r As Double
Try
rpt = LoadReport("C:\ErrorPlugin\bin\Debug\ErrorPlugin.dll")
r = rpt.SimpleExample()
Catch ex As Exception
MsgBox(ex.Message & vbCrLf & ex.StackTrace)
If ex.InnerException IsNot Nothing Then
MsgBox(ex.InnerException.StackTrace)
End If
End Try
End Sub
Public Function LoadReport(ByVal FileName As String) As Object
Dim m_ReportAssembly As [Assembly]
Dim m_ReportClass As Type
Dim rpt As Object
Try
m_ReportAssembly = Assembly.LoadFrom(FileName)
For Each m_ReportClass In m_ReportAssembly.GetTypes
If m_ReportClass.Name.ToLower = "ErrorPlugin".ToLower Then
rpt = Activator.CreateInstance(m_ReportClass)
Exit For
End If
Next
Return rpt
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
End Class
Can you see what happens if you just Throw, not Throw ex? From memory, "throw ex" does a copy while "throw" actually rethrows the caught exception. I guess your "throw ex" is effectively resetting the stack trace to your local code.
MSDN says if you're rethrowing exceptions you should add value to it by wrapping it in a new exception, otherwise you might as well not bother with try/catch in your example.
Do you have the debug symbols for these external DLL's? If you look at the stack trace, and it reads "External Code", that should be expanded into the DLL stack if you have the DLL debug symbols loaded while debugging, since the symbols will provide your debugger with the necessary info to walk the stack.
Either do this by manually loading the symbols, via the Modules Window in the Debug menu, or running against a debug build of the DLL.

Unstructured Exception Handling in VB.NET 2005/2008

I have a few VB.NET programs to maintain, that have been ported from VB6 and use the old style Unstructured Exception Handling:
On Error GoTo yyy
My question is, can I still get a stack trace while using Unstructured Exception Handling, or do I have to convert them all to Structured Exception Handling (Try/Catch) in order to catch an exception with its full stack trace.
Here's a way to get the stack trace to the line that caused the exception, unlike the other answer which just traces to the routine where your error handler is. The error might have occurred in a different routine.
In the unstructured error handlers, just use the GetException property of the Err object to access the underlying exception - then use the StackTrace property. Like this:
Public Class Form1
Public Sub New()
' This call is required by the Windows Form Designer.'
InitializeComponent()
' Add any initialization after the InitializeComponent() call.'
On Error GoTo ErrHandle
Call test()
Exit Sub
ErrHandle:
MsgBox("Stack trace " & Err.GetException.StackTrace)
Exit Sub
End Sub
Private Sub test()
Call test2()
End Sub
Private Sub test2()
Dim d(2) As Double
MsgBox(d(-1))
End Sub
End Class
As you know yourself, all things being equal, one should always use structured exception handling. However, if you can't, you can get your own stack trace by using the StackTrace class.
NB: Calls to stack trace are expensive, and should only be used in - ahem - 'exceptional' circumstances.
e.g
MethodName = (New StackFrame(0)).GetMethod.Name ' Get the current method
MethodName = (New StackFrame(1)).GetMethod.Name ' Get the Previous method
MethodName = (New StackFrame(2)).GetMethod.Name ' Get the method before that