Global Exception Handling in VB

Hello, I have this project that is experiencing some problems with what should be my code 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 am trying to globally catch all exceptions and create a log file at runtime that works fine in the debugger (exception handling and writing to a text file), but cannot catch any unhandled exceptions after I create it in the installation project and install into the car, what am I missing? Do I need to include additional components in my installation project? Help will be greatly appreciated

+5
source share
1 answer

There is already a way to handle exceptions for the entire application. Attaching a handler to a form means that they will only be caught and logged if and so far this form has been opened.

  • Go to Project โ†’ Properties โ†’ Application and click on the โ€œView Applicationsโ€ button at the bottom.

  • ApplicationEvents.vb opens.

  • Select (MyApplicationEvents) in the left menu; and UnhandledException on the right. This opens up the usual 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 throw exceptions until the IDE is triggered, because VS catches them first so you can see and fix them.

+7
source

All Articles