在 VB 中处理全局异常

Handle global exceptions in VB

你好,我的这个项目遇到了一些问题,这些问题应该是我的 "problem" 处理程序的代码。

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

我正在尝试全局捕获所有异常并在运行时创建日志文件,这在调试器(异常处理和文本文件写入)中工作正常,但在我在安装项目中构建它并安装到之后无法捕获任何未处理的异常机器。我错过了什么?我是否需要在我的设置项目中包含额外的组件?将不胜感激

已经有一种方法可以处理整个应用程序的异常。将处理程序嵌入表单意味着它们只会在该表单打开时被捕获和记录。

  1. 转到 项目 -> 属性 -> 应用程序 然后单击 "View Application Events" 按钮 at/near 底部。

  2. 这将打开 ApplicationEvents.vb

  3. Select (MyApplicationEvents) 在左侧菜单中; UnhandledException 在右边。这将打开一个典型的事件处理程序,您可以向其中添加代码:

    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
    

当 IDE 是 运行 时,这不会捕获异常,因为 VS 首先捕获它们,以便您可以看到它们并修复它们。