在应用程序级别处理异常

时间:2013-12-04 06:38:32

标签: vb.net

我有一个vb.net主桌面应用程序,还有主要应用程序的支持应用程序。

我必须对应用程序中的所有方法进行异常处理,但不希望在每个方法或事件单击中放置try catch。

是否有任何集中的异常处理方式。

其次,我可以避免任何异常并保持应用程序运行而不会发生任何崩溃。 我的意思是代替崩溃,我可以向用户显示是/否消息。

2 个答案:

答案 0 :(得分:2)

关于你的第一个问题:     是的,有一个集中的地方可以捕获应用程序级异常。检查申请活动:

Namespace My

' The following events are available for MyApplication:
' 
' Startup: Raised when the application starts, before the startup form is created.
' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
' UnhandledException: Raised if the application encounters an unhandled exception.
' StartupNextInstance: Raised when launching a single-instance application and the application is already active. 
' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
Partial Friend Class MyApplication

    Private Sub MyApplication_UnhandledException(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
        ' Log it?
        ' handle it? 
    End Sub

End Class

End Namespace

关于第二个问题,有几种方法可以让您的应用程序在不崩溃的情况下运行:

  1. 捕获未处理的异常并只显示消息
  2. 有一个MDI父窗口并在子窗体中捕获异常
  3. 使用服务并在服务级别处理异常
  4. 查看互联网以获取更多选择....

答案 1 :(得分:1)

Main子过程中,您可以订阅Application.ThreadException事件并强制所有其他非线程UI异常处理,如下所示:

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
  

注意:当在应用程序的根目录发生致命错误时保持程序运行不是一个好主意,因为系统可能处于无效状态并允许用户继续工作可能会进一步损坏系统中的数据。

相关问题