处理VB中的全局异常

时间:2015-05-27 16:25:38

标签: vb.net exception exception-handling

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

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 个答案:

答案 0 :(得分:10)

已经有办法处理整个应用程序的异常。在表单中嵌入处理程序意味着只有在该表单打开时才会捕获并记录它们。

  1. 转到项目 - >属性 - >应用程序并单击"查看应用程序事件"底部/靠近底部的按钮。

  2. 这将打开ApplicationEvents.vb

  3. 在左侧菜单中选择(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
    
  4. 这在IDE运行时不会捕获异常,因为VS首先捕获它们,以便您可以看到它们并修复它们。

相关问题