Reputation: 3009
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.
Upvotes: 4
Views: 7624
Reputation: 56697
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
.
Upvotes: 1
Reputation: 9362
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
Upvotes: 3
Reputation: 47367
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.
Upvotes: 1