【问题标题】:Handle global exceptions in VB在 VB 中处理全局异常
【发布时间】:2015-08-09 20:58:01
【问题描述】:

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

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

我正在尝试全局捕获所有异常并在运行时创建日志文件,这在调试器中运行良好(异常处理和文本文件写入)但在我在安装项目中构建并安装到机器后无法捕获任何未处理的异常.我错过了什么?我是否需要在我的设置项目中包含其他组件?非常感谢您的帮助

【问题讨论】:

  • 处理程序是否运行 - 即。如果您将MessageBox 移动到处理程序的第一行,您看到了吗?可能是您在处理程序中遇到错误(例如围绕日志记录?)
  • 我尝试将 MessageBox 移动到处理程序的第一行,是的,它出现了。我尝试将断点放在处理程序的开头并介入并直接通过处理程序
  • 运行应用程序的用户对日志文件的权限是否正常?
  • 是的 myFilePath 指向 appdata 本地文件夹
  • OK - 所以如果你将 MessageBox 移动到处理程序的第一行,它会显示在应用程序的构建版本上(即正在调用处理程序)但不会发生日志记录?

标签: vb.net exception exception-handling


【解决方案1】:

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

  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
    

这不会在 IDE 运行时捕获异常,因为 VS 会先捕获它们,因此您可以查看它们并修复它们。

【讨论】:

    猜你喜欢
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 2011-09-29
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多