-
May 23rd, 2022, 10:08 PM
#1
Thread Starter
Addicted Member
UnhandledException Doesn't Work
I'm trying to catch all the unhandled exceptions in my application with UnhandledException. My code is shown below. I understand that I have to build the application (Control F5) in release mode and run the exe file in the bin directory. But, that doesn't seem to be working. I don't get the MessageBox error. The WriteToErrorLog line writes the error to a txt file, but it doesn't do anything either. The WriteToErrorLog works fine in a Try Catch block. Any ideas why UnhandledException is not working for me? Do I need to add any code in another place in my project? Thanks in advance.
Code:
Namespace My
Partial Friend Class MyApplication
Private Sub MyApplication_UnhandledException(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
Dim el As New ErrorLogger
el.WriteToErrorLog(e.Exception.ToString, e.Exception.InnerException.ToString(), "Error, Unhandled Exception")
MessageBox.Show(e.Exception.ToString & e.Exception.InnerException.ToString()) '<-- the exception object
Console.WriteLine("error: " + e.Exception.ToString)
e.ExitApplication = False '<-- True if you want the application to close; false to continue - if it can
End Sub
End Class
End Namespace
Code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'CODE TO CRASH PROGRAM And TEST UNHANDLED EXCEPTIONS
Dim MyIVar As Integer = 1
MyIVar /= 0
End Sub
-
May 23rd, 2022, 11:03 PM
#2
Re: UnhandledException Doesn't Work
The issue is that your exception handling code is throwing another exception. If you had paid attention in the debugger then you'd have seen that the InnerException for the exception you're throwing is Nothing. In that case, what do you think this is going to do:
Code:
e.Exception.InnerException.ToString()
It's going to throw a NullReferenceException. The simple fix is to do this:
Code:
e.Exception.InnerException?.ToString()
so that will evaluate to Nothing if there's no InnerException. A more robust solution might be something like this:
vb.net Code:
Dim ex = e.Exception
Dim errorLog = ex.ToString()
While ex.InnerException IsNot Nothing
ex = ex.InnerException
errorLog &= Environment.NewLine & ex.ToString()
End While
-
May 24th, 2022, 05:09 PM
#3
Thread Starter
Addicted Member
Re: UnhandledException Doesn't Work
Nope, I didn't have any luck. I tried both codes below and it didn't work. I ran the exe file in the bin directory. Your original suggested code gave me an error, so I defined variable ex as an object. Not sure if that is correct.
Code:
Namespace My
Partial Friend Class MyApplication
Private Sub MyApplication_UnhandledException(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
Dim el As New ErrorLogger
el.WriteToErrorLog(e.Exception.ToString, e.Exception.InnerException?.ToString(), "Error, Unhandled Exception")
MessageBox.Show(e.Exception.ToString & e.Exception.InnerException?.ToString()) '<-- the exception object
Console.WriteLine("error: " + e.Exception.ToString)
e.ExitApplication = False '<-- True if you want the application to close; false to continue - if it can
End Sub
End Class
End Namespace
Code:
Namespace My
Partial Friend Class MyApplication
Private Sub MyApplication_UnhandledException(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
Dim ex As Object = e.Exception
Dim errorLog As String = ex.ToString()
While ex.InnerException IsNot Nothing
ex = ex.InnerException
errorLog &= Environment.NewLine & ex.ToString()
End While
Dim el As New ErrorLogger
el.WriteToErrorLog(e.Exception.ToString, e.Exception.InnerException?.ToString(), "Error, Unhandled Exception")
MessageBox.Show(e.Exception.ToString & e.Exception.InnerException?.ToString()) '<-- the exception object
Console.WriteLine("error: " + e.Exception.ToString)
e.ExitApplication = False '<-- True if you want the application to close; false to continue - if it can
End Sub
End Class
End Namespace
-
May 24th, 2022, 08:46 PM
#4
Re: UnhandledException Doesn't Work
There's a lot to address here but I just can't bear it right now. What I will suggest is that you take it back to basics, as you should have done from the start. Forget the InnerException for now and try just logging the exception itself. As you should ALWAYS do when things don;t work, simplify the code as much as possible and then add to it until it breaks to se where the issue is.
-
May 27th, 2022, 01:31 PM
#5
Re: UnhandledException Doesn't Work
It seems you want to be able to walk through all the exceptions on the call stack through use of the InnerException property. You need to do this recursively if you want to capture the data on all of them:-
Code:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler My.Application.UnhandledException, AddressOf EH_UnhandledException
'Lets imitate an exception chain that typically comes
'from multiple levels in the call stack.
Dim ex As New Exception("Bombing out!", New Exception("Internal Bombout!", New Exception("Really deep error", New Exception("Now this is too deep!"))))
Throw ex
End Sub
Private Sub EH_UnhandledException(ByVal sender As Object, ByVal e As ApplicationServices.UnhandledExceptionEventArgs)
MessageBox.Show(ExceptionToSting(e.Exception))
End Sub
Private Function ExceptionToSting(ByVal e As Exception) As String
'This function recursively walks the Exception chain.
'***********************************************************
Dim msg As String = e.Message & Environment.NewLine & Environment.NewLine
If e.InnerException IsNot Nothing Then
Return msg & ExceptionToSting(e.InnerException)
Else
Return msg
End If
End Function
End Class
Output:-
-
May 30th, 2022, 06:08 AM
#6
Thread Starter
Addicted Member
Re: UnhandledException Doesn't Work
Niya, I tried that and it worked for me. The problem for me is that I'm trying to write the errors to a log file in the app directory, but that part is not working for me.
After more research, I found out that there are three ways to deal with these unhandled errors. They are ApplicationDomain, System.Windows, and My.Application.UnhandledException. I'm using the following code and it works, but it send the error files to a weird hidden directory "C:\Users\user\AppData\Roaming\MyCompany\My". Now, I'm trying to figure out how to change the destination path. Microsoft has article about this, but it is clear as mud.
Code:
Namespace My
Partial Friend Class MyApplication
Private Sub MyApplication_UnhandledException(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
My.Application.Log.WriteEntry("######## UNHANDLED EXCEPTION, WindowsFormsApplicationBase.UnhandledException Event ########")
My.Application.Log.WriteException(e.Exception, TraceEventType.Critical, "")
My.Application.Log.DefaultFileLogWriter.ToString()
My.Application.Log.WriteEntry(e.Exception.GetType.ToString())
My.Application.Log.WriteEntry(e.Exception.StackTrace.ToString())
My.Application.Log.WriteEntry(DateTime.Now.ToString())
My.Application.Log.WriteEntry("-----------------------------------------------------------------------------------------------")
e.ExitApplication = False
End Sub
End Class
End Namespace
-
May 30th, 2022, 09:02 AM
#7
Re: UnhandledException Doesn't Work
You generally should not write to the app directory, and generally wont be able to - as Windows will block writing to protected folders (such as ProgramFiles etc), because that is what malware will do to infect programs etc.
AppData is a standard place for things like log files, and there are some other folders that are potentially appropriate too depending on circumstances (such as MyDocuments and ProgramData).
Here is some very old (Windows 2000) guidance on folder usage, which still applies today: https://docs.microsoft.com/en-us/pre...N#w2kcli_req42
-
May 30th, 2022, 09:07 AM
#8
Thread Starter
Addicted Member
Re: UnhandledException Doesn't Work
Well, I was able to do it. You need to add the following code to the app.config file in your project. All the unhandled errors are been sent to a directory "Errors" in my app bin directory.
Code:
<listeners>
<add name="FileLog"/>
</listeners>
Code:
<sharedListeners>
<!--NEXT LINE SENDS UNHANDLED ERRORS TO THE APP DIRECTORY ERRORS\APPNAME.LOG FILE-->
<add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter" location="Custom" customlocation="Errors\" />
</sharedListeners>
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
|