Global exception handling in .NET?

The whole concept of exception handling gives me headaches. Currently, what I want to do is to handle certain exceptions, which I'm sure I can handle. On the other hand, I want to terminate the application if an exception is thrown that I do not know how to handle. When I put try-catch blocks in my source code, it looks ugly because there are a lot of them. Is there a global exception handling mechanism, for example, an event that is fired after an unhandled exception is dispatched? Thus, I can display an error message for the user and terminate the application, rather than repeating this process again and again throughout the entire source code.

PS I want to terminate the application in such a scenario, because I am afraid that the program may start to work incorrectly after an unhandled exception is sent.

+3
source share
3 answers

At least in C # you can assign a global "unhandled exception handler." To do this, you must assign a new handler AppDomain.CurrentDomain.UnhandledException.

+2
source

In VB.NET, you need to handle the My.Application.UnhandledException Event:

Example (from MSDN):

Private Sub MyApplication_UnhandledException( _
    ByVal sender As Object, _
    ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs _
) Handles Me.UnhandledException
    My.Application.Log.WriteException(e.Exception, _
        TraceEventType.Critical, _
        "Unhandled Exception.")
End Sub
+3
source

-? , . Application_Error .

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)  
    ''# Code that runs when an unhandled error occurs  
    Dim exception As Exception = HttpContext.Current.Server.GetLastError()  
    Dim emailerrors As Boolean = If(LCase(AppSettings.GetAppValue("EmailErrors")) = "yes", True, False)  
    HealthMonitor.Log(exception, emailerrors)  
End Sub 

What this will do is a trap for every unhandled error (IE: errors outside of your attempt / catch and their registration). From there (I redirect) you can stop your application or do anything.

0
source

Source: https://habr.com/ru/post/1753847/


All Articles