|
-
Mar 4th, 2025, 08:36 PM
#1
Thread Starter
Addicted Member
VB.Net: Cannot Handle Unhandled Exception When Inheriting Forms Project
I have have a Solution that occasionally crashes and I would like to log the exception. I have added code to handle unhandled exception, but it does not get called. Perhaps this is related to inheritance.
To simplify the investigation, I created an experimental Solution to test the exception handling. It has two Projects, WindowsAppSource and WindowsAppTest. WindowsAppTest inherits WindowsAppSource. A divide by zero is used to create an exception.
WindowsAppSource has one control, Button1:
Code:
Protected WithEvents Button1 As Button
- - -
Protected Overridable Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
WindowsAppTest inherits WindowsAppSource and overrides Button1:
Code:
Public Class Form1
Inherits WindowsAppSource.Form1
- - -
Protected Overrides Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim z As Integer = 0
Dim i As Integer = 1 \ z
End Sub
End Class
Both projects have the same methods added to handle unhandled exceptions, as suggested on this fine forum, but none of these get called.
In ApplicationEvents.vb (of both projects):
Code:
Partial Friend Class MyApplication
Private Sub MyApplication_UnhandledException(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
Dim exLogPath As String = System.IO.Path.Combine(My.Application.Info.DirectoryPath, "UnhandledExceptions")
If Not System.IO.Directory.Exists(exLogPath) Then MkDir(exLogPath?
Dim fullPath As String = System.IO.Path.Combine(exLogPath, $"ExceptionLog-{Format(Now, "yyyy.MM.dd")}.txt")
Using sw = New IO.StreamWriter(fullPath, True)
sw.WriteLine($"{vbCrLf}{Format(Now, "yyyy/MM/dd HH:mm:ss")}{vbCrLf}Sender: {sender}{vbCrLf}{e.Exception}{vbCrLf}")
End Using
End Sub
End Class
In Application.Designer.vb (of both projects):
Code:
Namespace My
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> Public Sub New() ...
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> Protected Overrides Sub OnCreateMainForm() ...
Private Sub MyApplicationUnhandledException(ByVal sender As Object,
ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
Dim exLogPath As String = System.IO.Path.Combine(My.Application.Info.DirectoryPath, "UnhandledExceptions")
If Not System.IO.Directory.Exists(exLogPath) Then MkDir(exLogPath?
Dim fullPath As String = System.IO.Path.Combine(exLogPath, $"ExceptionLog-{Format(Now, "yyyy.MM.dd")}.txt")
Using sw = New IO.StreamWriter(fullPath, True)
sw.WriteLine($"{vbCrLf}{Format(Now, "yyyy/MM/dd HH:mm:ss")}{vbCrLf}Sender: {sender}{vbCrLf}{e.Exception}{vbCrLf}")
End Using
End Sub
End Class
End Namespace
(I kept getting "403 Forbidden" with the closing parentheses in the MkDir lines, so I replaced them with question marks)
I will appreciate any suggestions of how the exception can be logged.
-
Mar 4th, 2025, 09:07 PM
#2
Re: VB.Net: Cannot Handle Unhandled Exception When Inheriting Forms Project
The issue seems obvious: you don't have permission to create a directory where you're trying to. You seem to be trying to do so in the program folder, which would not be possible for a standard user if the app is running from the Program Files folder. Windows provides numerous special directories, the paths of which can be accessed using Environment.GetFolderPath or My.Computer.FileSystem.SpecialDirectories. The app data folder seems the most appropriate option for error logging.
-
Mar 5th, 2025, 01:00 PM
#3
Thread Starter
Addicted Member
Re: VB.Net: Cannot Handle Unhandled Exception When Inheriting Forms Project
Hi jmcilhinney,
Thanks for looking into this. I did some more experimenting, this is what I found.
Breakpoints put in the unhandled exception sub do not get hit.
The file is written when the divide by zero is wrapped in a try/catch.
Code:
Protected Overrides Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim z As Integer = 0
Dim i As Integer = 1 \ z
Catch ex As Exception
Dim exLogPath As String = System.IO.Path.Combine(My.Application.Info.DirectoryPath, "UnhandledExceptions")
If Not System.IO.Directory.Exists(exLogPath) Then MkDir(exLogPath?
Dim fullPath As String = System.IO.Path.Combine(exLogPath, $"ExceptionLog-{Format(Now, "yyyy.MM.dd")}.txt")
Using sw = New IO.StreamWriter(fullPath, True)
sw.WriteLine($"{vbCrLf}{Format(Now, "yyyy/MM/dd HH:mm:ss")}{vbCrLf}Sender: {sender}{vbCrLf}{ex}{vbCrLf}")
End Using
End Try
End Sub
Changing the file paths to c:\temp did not help.
The problem is not inheritance related as I originally suspected.
After changing WindowsAppTest back to Inherits System.Windows.Forms.Form, the breakpoints still are not hit.
I need to figure out why the unhandled exception subs are not being called.
If you have any ideas regarding this, please let me know.
-
Mar 7th, 2025, 06:15 PM
#4
New Member
Re: VB.Net: Cannot Handle Unhandled Exception When Inheriting Forms Project
 Originally Posted by ThatSamiam
Breakpoints put in the unhandled exception sub do not get hit.
You need multiple hooks to catch more exceptions (still not all, but most). I have this in my app's Application.xaml.vb (.NET Core 6):
Code:
Private Sub Application_Startup(sender As Object, e As StartupEventArgs)
AddHandler Me.DispatcherUnhandledException, AddressOf Application_DispatcherUnhandledException
AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf OnUnhandledException
AddHandler TaskScheduler.UnobservedTaskException, AddressOf OnUnobservedTaskException
End Sub
Private Sub OnUnhandledException(sender As Object, e As UnhandledExceptionEventArgs)
logException(e.ExceptionObject)
End Sub
Private Sub OnUnobservedTaskException(sender As Object, e As UnobservedTaskExceptionEventArgs)
logException(e.Exception)
e.SetObserved()
End Sub
Private Sub Application_DispatcherUnhandledException(sender As Object, e As System.Windows.Threading.DispatcherUnhandledExceptionEventArgs)
logException(e.Exception)
End Sub
Private Sub logException(ex As Exception)
Dim folder As String = IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
IO.File.AppendAllLines(IO.Path.Combine(folder, "error.log"), {String.Format("-----{0:d} {0:HH:mm:ss}-----", DateTime.Now)})
While Not ex Is Nothing
IO.File.AppendAllLines(IO.Path.Combine(folder, "error.log"), {ex.Message, ex.StackTrace?.ToString()})
ex = ex.InnerException
End While
End Sub
-
Mar 12th, 2025, 04:18 PM
#5
Thread Starter
Addicted Member
Re: VB.Net: Cannot Handle Unhandled Exception When Inheriting Forms Project
Thanks laila,
I did not specify that this project is a Windows Forms App (.NET Framework), using Framework 4.8, so Dispatcher Unhandled Exception does apply (not WPF).
I did try catching Unobserved Task Exceptions as you suggested, but no luck there.
The only way I have found to see the unhandled exceptions is with First Chance Exception, but that also gets handled exceptions, so all or nothing.
For the record, here is the First Chance Exception related code:
Code:
Public Shared Sub AppDomain_FirstChanceException(ByVal sender As Object, ByVal e As Runtime.ExceptionServices.FirstChanceExceptionEventArgs)
WriteLog("App_Domain_First_Chance_Exception", sender, e.Exception.Message)
End Sub
Protected Overrides Function OnStartup(e As ApplicationServices.StartupEventArgs) As Boolean
AddHandler AppDomain.CurrentDomain.FirstChanceException, AddressOf AppDomain_FirstChanceException
Return MyBase.OnStartup(e)
End Function
-
May 2nd, 2025, 09:59 PM
#6
New Member
Re: VB.Net: Cannot Handle Unhandled Exception When Inheriting Forms Project
Try this ;-)
Code:
Module Program
Sub Main()
' Catch UI thread exceptions
AddHandler Application.ThreadException, AddressOf Application_ThreadException
' Catch non-UI thread exceptions
AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf CurrentDomain_UnhandledException
Application.Run(New MainForm())
End Sub
Private Sub Application_ThreadException(sender As Object, e As ThreadExceptionEventArgs)
MessageBox.Show("UI Thread Exception: " & e.Exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
' Optional: log the exception
End Sub
Private Sub CurrentDomain_UnhandledException(sender As Object, e As UnhandledExceptionEventArgs)
Dim ex As Exception = TryCast(e.ExceptionObject, Exception)
MessageBox.Show("Non-UI Thread Exception: " & ex?.Message, "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
' Optional: log the exception
End Sub
End Module
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|