Friday, April 29, 2011

Catch Exception in VS2010

I am under Visual Studio 2010 in a Windows Application Project with framework 4. So to achieve your need you right click on My Project Folder and click open. Under Application tab (the default one) click on the latest button View Application Events. This will create an ApplicationEvents class. Open it and copy paste this code :






Public Sub My_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup



AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf CurrentDomain_UnhandledException

AddHandler System.Windows.Forms.Application.ThreadException, AddressOf UIThreadException



End Sub





Private Sub UIThreadException(ByVal sender As Object, ByVal ex As ThreadExceptionEventArgs)



Try



WriteErrorLog(ex.Exception)



Catch



Finally



End Try



End Sub



' Handle the UI exceptions by showing a dialog box, and asking the user whether

' or not they wish to abort execution.

' NOTE: This exception cannot be kept from terminating the application - it can only

' log the event, and inform the user about it.

Private Sub CurrentDomain_UnhandledException(ByVal sender As Object, ByVal e As System.UnhandledExceptionEventArgs)

Try

Dim ex As Exception = CType(e.ExceptionObject, Exception)



WriteErrorLog(ex)



Catch exc As Exception



End Try

End Sub



From method:







WriteErrorLog(ByVal ex As Exception)





You can create your own method to log the error. Note that you do not need of :







Application.SetUnhandledExceptionMode(UnhandledExceptionMode.Automatic)





At all and even less turning off the application framework.



Hope this will help someone.



dalkar69

No comments:

Post a Comment