2015-05-27 77 views
5

您好,我有这个项目遇到了一些问题,应该是什么应该是我的代码“问题”处理程序。在VB中处理全局异常

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 

我试图在全球范围内捕获所有异常,并创建运行时日志文件,这在调试器(异常处理和文本文件写)工作正常,但之后我在安装项目建设无法赶上任何未处理的异常和安装到机器中。我错过了什么?我是否需要将其他组件添加到我的安装项目中?帮助将不胜感激

+0

处理程序是否运行 - 即。如果你将'MessageBox'移动到处理程序的第一行,你会发现它吗?这可能是你在处理程序中出现错误(例如在日志记录中) – theduck

+0

我试着将MessageBox移动到处理程序的第一行,并且显示出来。我尝试将断点放置到处理程序的开始处,并直接通过处理程序 – Adrian

+0

运行应用程序的用户的日志文件权限是否正确? – theduck

回答

7

已经有一种方法来处理整个应用程序的异常。将处理程序嵌入到表单中意味着只有当该表单处于打开状态时才会捕获并记录该处理程序。

  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第一捉住他们,所以你可以看到他们和解决这些问题这不会捕获异常。