В вашем Main
Подпроцедура, вы можете подписаться на Application.ThreadException
события и заставить все другие исключения не-нить пользовательского интерфейса в обработчике, как это:
Public Shared Sub Main()
' Add the event handler for handling UI thread exceptions
AddHandler Application.ThreadException, AddressOf HandleThreadException
' Set the unhandled exception mode to force all Windows Forms errors to go
' through our handler
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException)
' Add the event handler for handling non-UI thread exceptions
AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf HandleUnhandledException
' Runs the application.
Application.Run(New YourForm())
End Sub
' Handle the UI exceptions by showing a dialog box, and asking the user whether
' or not they wish to abort execution.
Private Shared Sub Form1_UIThreadException(ByVal sender As Object, ByVal t As ThreadExceptionEventArgs)
Dim result As System.Windows.Forms.DialogResult = _
System.Windows.Forms.DialogResult.Cancel
Try
result = ShowThreadExceptionDialog("Windows Forms Error", t.Exception)
Catch
Try
MessageBox.Show("Fatal Windows Forms Error", _
"Fatal Windows Forms Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop)
Finally
Application.Exit()
End Try
End Try
' Exits the program when the user clicks Abort.
If result = DialogResult.Abort Then
Application.Exit()
End If
End Sub
' Handle the UI exceptions by showing a dialog box, and asking the user whether
' or not they wish to abort execution
Private Shared Sub CurrentDomain_UnhandledException(ByVal sender As Object, _
ByVal e As UnhandledExceptionEventArgs)
Try
Dim ex As Exception = CType(e.ExceptionObject, Exception)
Dim errorMsg As String = "An application error occurred. Please contact the adminstrator " & _
"with the following information:" & ControlChars.Lf & ControlChars.Lf
' Since we can't prevent the app from terminating, log this to the event log.
If (Not EventLog.SourceExists("ThreadException")) Then
EventLog.CreateEventSource("ThreadException", "Application")
End If
' Create an EventLog instance and assign its source.
Dim myLog As New EventLog()
myLog.Source = "ThreadException"
myLog.WriteEntry((errorMsg + ex.Message & ControlChars.Lf & ControlChars.Lf & _
"Stack Trace:" & ControlChars.Lf & ex.StackTrace))
Catch exc As Exception
Try
MessageBox.Show("Fatal Non-UI Error", "Fatal Non-UI Error. Could not write the error to the event log. " & _
"Reason: " & exc.Message, MessageBoxButtons.OK, MessageBoxIcon.Stop)
Finally
Application.Exit()
End Try
End Try
End Sub
' Creates the error message and displays it.
Private Shared Function ShowThreadExceptionDialog(ByVal title As String, ByVal e As Exception) As DialogResult
Dim errorMsg As String = "An application error occurred. Please contact the adminstrator " & _
"with the following information:" & ControlChars.Lf & ControlChars.Lf
errorMsg = errorMsg & e.Message & ControlChars.Lf & _
ControlChars.Lf & "Stack Trace:" & ControlChars.Lf & e.StackTrace
Return MessageBox.Show(errorMsg, title, MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop)
End Function
Примечание: Это не хорошо чтобы поддерживать работу программы при возникновении фатальной ошибки, которая попадает в корень приложения, поскольку система может находиться в недопустимом состоянии и позволяет пользователю продолжать работу, может привести к повреждению данных в системе.
У меня нет основного метода в приложении mmy. Я новичок в приложении Windows, так что есть ли другое место, где я могу разместить обработку исключений. – user3060430
Щелкните правой кнопкой мыши проект Winform, выберите приложение и нажмите «Просмотреть события приложения» http://msdn.microsoft.com/en-us/library /f2bys999(v=vs.90).aspx – Ric