views:

27

answers:

3

The whole concept of exception handling is giving me headaches. Currently, what I want to do is to handle specific exceptions that I am positively sure I can handle. On the other hand, I want to terminate the application if an exception that I dont know how to handle is thrown. When I place try-catch blocks in my source code, it looks ugly because there are many of those. Is there a global exception handling mechanism like an event that is fired once an unhandled exception is thrown? That way I can display an error message to the user and terminate the application instead of reiterating this process over and over throughout my source code.

P.S. I want to terminate the application in such a scenario because I am afraid the program might begin functioning improperly once an unhandled exception is thrown.

A: 

are you building a win forms app or a web app? I wrote a blog entry on a custom Health Monitor, whereby you can submit exceptions to a database. Then in the Application_Error method you add code like this.

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 trap every unhandled error (IE: errors outside your try/catch and log them. From there (I redirect) you can stop your application, or do whatever you like.

rockinthesixstring
I am building a WPF application, but I have experience in Win Forms.
+1  A: 

In VB.NET you need to handle 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
Anax
A: 

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

Thorsten Dittmar
I see that the event handler kills the process. I want to show a user control and have it terminate the application, but the user control is not shown. The only thing I can display is a message box.
You could try to invoke a public method on your main window that shows the view, but I'm not sure whether that would work. IIRC there's a flag in the event's parameter that you can use to determine whether the application should quit or not.
Thorsten Dittmar
The public method worked only when it had a message box in it. It seems message boxes are special. Also, e.isTerminating is read-only.