加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

.net – Catch块没有捕获异常

发布时间:2020-12-17 00:02:20 所属栏目:大数据 来源:网络整理
导读:我有一个子窗体,它在Load事件处理程序中抛出ApplicationException(故意用于测试目的).父表单在Try … Catch ex As Exception块中包装ChildForm.Show()方法. catch块只显示一条消息并关闭子表单.在visual studio 2008(.net 3.5 sp1)中调试时,所有工作都按预期
我有一个子窗体,它在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 UnhandledExceptionTest2WindowsApplication1Form2.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(),现在可以捕获异常了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读