.net – Catch块没有捕获异常

我有一个子窗体,它在Load事件处理程序中抛出ApplicationException(故意用于测试目的).父表单在Try … Catch ex As Exception块中包装ChildForm.Show()方法. catch块只显示一条消息并关闭子表单.在visual studio 2008(.net 3.5 sp1)中调试时,所有工作都按预期工作.但是,当我在visual studio之外运行它时,Catch块似乎错过了,并且发生了未处理的异常.知道为什么会这样吗?

谢谢.

示例代码

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles Button1.Click
        Dim f2 As Form2

        f2 = New Form2

        Try
            MessageBox.Show("opening form 2")
            f2.ShowDialog()
        Catch ex As Exception
            f2.Close()
            MessageBox.Show("Form 2 closed.")
        End Try
    End Sub

End Class

Public Class Form2

    Private Sub Form2_Load(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles MyBase.Load
        Throw New ApplicationException("Test Form_Load")
    End Sub

    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
    End Sub

End Class

堆栈跟踪:

 System.ApplicationException:
 Test Form_Load   at WindowsApplication1.Form2.Form2_Load(Object sender,EventArgs e)
 in UnhandledExceptionTest2\WindowsApplication1\Form2.vb
 System.Windows.Forms.Form.OnLoad(EventArgs e)
 System.Windows.Forms.Form.OnCreateControl()
 System.Windows.Forms.Control.CreateControl(Boolean fignoreVisible)
 System.Windows.Forms.Control.CreateControl()
 System.Windows.Forms.Control.WmShowWindow(Message& m)    at
 System.Windows.Forms.Control.WndProc(Message&> m)    at
 System.Windows.Forms.ScrollableControl.WndProc(Message&> m)    at
 System.Windows.Forms.ContainerControl.WndProc(Message&> m)    at
 System.Windows.Forms.Form.WmShowWindow(Message&> m)    at
 System.Windows.Forms.Form.WndProc(Message&> m)    at
 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&> m)    at
 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&> m)    at
 System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr
 lparam)
Form.Load事件的行为与Windows窗体中的大多数其他事件的行为相同.它由消息循环调度,在这种情况下,当Windows发送WM_SHOWWINDOW消息时.消息循环中有一个异常处理程序可以防止未捕获的异常终止消息循环.该异常处理程序引发Application.ThreadEvent事件.认事件处理程序显示未处理的异常对话框.

简而言之,您无法在按钮单击处理程序中捕获Load事件中引发的异常.除了在Load事件处理程序本身中捕获和处理异常之外,很难做到正确,我建议您在表单中添加一个公共方法.像Initialize()之类的东西.将Load事件中的代码移动到该方法中.调用Show()方法调用Initialize(),现在可以捕获异常了.

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...