How to debug unhandle exception handling - vb.net

My current install of Visual Studio 2015 will not allow me to throw an unhandled exception while running code from the IDE. I want to exercise my unhandled exception code but my code:
Private Sub btnTest_Click(sender As System.Object, e As System.EventArgs) Handles btnTest.Click
Throw New System.Exception("An unhandled test exception has occurred.")
End Sub
only works during a normal runtime, not when the code is executed in the IDE.
How can I debug my unhandled exception code in the IDE?
I looked in Debug, Windows, Exception Settings but I don't see a way to do what I want to do. Is there another more global setting that will allow an unhandled exception without the IDE capturing the exception?
I'm using the ApplicationsEvents.vb to hook the event:
Namespace My
' The following events are available for MyApplication:
'
' Startup: Raised when the application starts, before the startup form is created.
' Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally.
' UnhandledException: Raised if the application encounters an unhandled exception.
' StartupNextInstance: Raised when launching a single-instance application and the application is already active.
' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
Partial Friend Class MyApplication
Private Sub MyApplication_UnhandledException(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
ExpLog.LogUnhandledException(e, sender)
e.ExitApplication = Not ExpLog.InformUser
End Sub
End Class
End Namespace
Resolution was to create a test stub that exercised the code that was called by the handler:
Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles btnMisc_Throw.Click
If ExpLog.InformUser() Then
MsgBox("Continue")
Else
MsgBox("End Program")
End If
ExpLog.LogMsgBox(New System.Exception("test unhandled exception"), "test LogMsgBox()",,, "programmer note")
End Sub
This doesn't allow for testing the handler but it does exercise the code the handler calls. Looking at some old comments I figured this out five+ years ago... :(

Add a handler to AppDomain.CurrentDomain.UnhandledException
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledExceptionHandler
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Throw New System.Exception("An unhandled test exception has occurred.")
End Sub
Public Shared Sub UnhandledExceptionHandler(ByVal sender As Object, ByVal args As UnhandledExceptionEventArgs)
MessageBox.Show(CType(args.ExceptionObject, Exception).Message)
End Sub

Related

Cannot access a disposed object in VB.NET

Having a small issue.
I am receiving a Cannot access a disposed object error for Form1
Upon clicking a menu item on the main form - the below Sub is called, which opens another form Form1
Private Sub ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem.Click
If (Not Form1.Visible) Then
Form1.Show(Me)
End If
End Sub
Within Form1, there is a Try block. If it isn't passed, Form1 should show a message box, before closing down. The message appears, but it's then that I receive the error (where it says Form1.Show(Me))
Private Sub Form1_Load(ByVal sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Try
'DO STUFF
Catch
MsgBox("Error loading in data. Please contact an administrator")
Me.Close()
Return
End Try
End Sub
I am quite new to this type of programming, and struggling to fix the problem even after searching similar problems. Could someone please assist or point me in the right direction?
EDIT: So looks like this is due to trying to close the form during the Load event. So my question now is, are there any simple alternatives? I've found ways of doing this in C#, but not a lot for vb.net
Here is one option:
Private loadFailed As Boolean = False
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
'...
Catch ex As Exception
loadFailed = True
End Try
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
If loadFailed Then
MessageBox.Show("Load failed")
Close()
End If
End Sub
In that case, the form will show with the message over it, then it will close when the message is dismissed. Here's an option that will not display the form:
Friend Module Form1Manager
Public Sub ShowForm1(owner As Form)
If Not Form1.Visible Then
Try
'...
'Pass data to Form1 here.
Form1.Show(owner)
Catch ex As Exception
MessageBox.Show("Load failed")
End Try
End If
End Sub
End Module
and, to use that:
Private Sub ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem.Click
Form1Manager.ShowForm1(Me)
End Sub

Handle global exceptions in VB

Hello I have this project experiencing some problems with what is supposed to be my codes for the "problem" handler.
Public Event UnhandledException As UnhandledExceptionEventHandler
Private Sub form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim currentDomain As AppDomain = AppDomain.CurrentDomain
AddHandler currentDomain.UnhandledException, AddressOf MyHandler
End Sub
Sub MyHandler(ByVal sender As Object, ByVal args As UnhandledExceptionEventArgs)
Dim e As Exception = DirectCast(args.ExceptionObject, Exception)
Using sw As New StreamWriter(File.Open(myFilePath, FileMode.Append))
sw.WriteLine(Date.now & e.toString)
End Using
MessageBox.Show("An unexcpected error occured. Application will be terminated.")
Application.Exit()
End Sub
Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
Throw New Exception("Dummy Error")
End Sub
I'm trying to globally catch all exceptions and create logfile during runtime, which works fine in the debugger(exception handling and textfile writing) but cannot catch any unhandled exceptions after I build it in the setup project and Installed into a machine. What am I missing? Do I need to include additional components to my setup project? Help would be greatly appreciated
There is already a way to handle exceptions for the entire application. Embedding the handler in a form means they would only be caught and logged if and while that form was open.
Go to Project -> Properties -> Application and click the "View Application Events" button at/near the bottom.
This will open ApplicationEvents.vb.
Select (MyApplicationEvents) in the left menu; and UnhandledException in the right. This opens an otherwise typical event handler to which you can add code:
Private Sub MyApplication_UnhandledException(sender As Object,
e As ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
Dim myFilePath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"badjuju.log")
Using sw As New StreamWriter(File.Open(myFilePath, FileMode.Append))
sw.WriteLine(DateTime.Now)
sw.WriteLine(e.Exception.Message)
End Using
MessageBox.Show("An unexcpected error occured. Application will be terminated.")
End
End Sub
This will not catch exceptions while the IDE is running because VS catches them first so you can see them and fix them.

VB.NET How do i use ApplicationEvents to catch an exception within a thread?

I have a piece of code in my ApplicationEvents.vb that is supposed to handle all exceptions:
Namespace My
' The following events are available for MyApplication:
'
' Startup: Raised when the application starts, before the startup form is created.
' Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally.
' UnhandledException: Raised if the application encounters an unhandled exception.
' StartupNextInstance: Raised when launching a single-instance application and the application is already active.
' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
Partial Friend Class MyApplication
Private Delegate Sub SafeApplicationThreadException(ByVal sender As Object, ByVal e As Threading.ThreadExceptionEventArgs)
Private Sub ShowDebugOutput(ByVal ex As Exception)
Dim frmD As New frmDebug()
frmD.rtfError.AppendText(ex.ToString())
frmD.ShowDialog()
Environment.Exit(0)
End Sub
Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
System.Windows.Forms.Application.SetUnhandledExceptionMode(UnhandledExceptionMode.Automatic)
AddHandler System.Windows.Forms.Application.ThreadException, AddressOf app_ThreadException
AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf AppDomain_UnhandledException
End Sub
Private Sub app_ThreadException(ByVal sender As Object, ByVal e As Threading.ThreadExceptionEventArgs)
If MainForm.InvokeRequired Then
MainForm.Invoke(New SafeApplicationThreadException(AddressOf app_ThreadException), New Object() {sender, e})
Else
ShowDebugOutput(e.Exception)
End If
End Sub
Private Sub AppDomain_UnhandledException(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
ShowDebugOutput(DirectCast(e.ExceptionObject, Exception))
End Sub
Private Sub MyApplication_UnhandledException(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
ShowDebugOutput(e.Exception)
End Sub
End Class
End Namespace
However, i have found that it will not catch exceptions from within, for example, a BGWorker_DoWork sub.
It will, however, catch exceptions on the same BGWorker_RunWorkerCompleted sub.
Is there a way for me to catch the exceptions from within the thread, without using Try-Catch?

Button.PerformClick() across thread

See this code:
Imports System.Threading
Private trd As Thread
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
trd = New Thread(AddressOf ThreadTask)
trd.IsBackground = True
trd.Start()
End Sub
Sub ThreadTask()
Thread.Sleep(50)
Button4.PerformClick()
End Sub
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Me.Close()
End Sub
I'm trying to simulate a button click from a different thread, but the following error occurs: "An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll", at the Button4.PerformClick() line.
How can I use this function across threads?
You need to execute UI commands on the same thread as the controls were created on. We can do this with a delegate. This can be done very easily with a lambda.
Replace Button4.PerformClick() with this:
Me.Invoke(Sub() Button4.PerformClick())

Close App When 2nd Form Closes

I've looked all over for a way to close the program if the 2nd form is closed
I have a boolean that is Set to True if the 2nd form is visible, but when the frmCourses.visible Check goes, I get the error in Debug mode An unhandled exception of type 'System.InvalidOperationException' occurred in HomeWork Helper.exe
If Ready Then
If frmCourses.Visible = False Then
Application.Exit()
End If
End if
In the 2nd Form, create a method for Form2_FormClosed
This code will be added:
Private Sub Form2_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
End Sub
Inside the Sub, add Application.Exit()
Result (With a Comment):
Private Sub Form2_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
'Closes the Application if the 2nd Form is Closed
Application.Exit()
End Sub