gpt4 book ai didi

.net - catch block 未捕获异常

转载 作者:行者123 更新时间:2023-12-02 06:41:04 25 4
gpt4 key购买 nike

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

谢谢。

示例代码:

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 事件。默认事件处理程序显示未处理的异常对话框。

长话短说,您无法捕获按钮 Click 处理程序中 Load 事件中引发的异常。除了在 Load 事件处理程序本身中捕获和处理异常(很难正确执行)之外,我建议您向表单添加一个公共(public)方法。类似Initialize()之类的东西。将代码从 Load 事件移至该方法中。调用 Show() 方法后调用 Initialize(),现在您可以捕获异常。

关于.net - catch block 未捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/389504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com