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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With