Module Module1
Public Sub Main()
AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledExceptionHandler
AddHandler Application.ThreadException, AddressOf ThreadExceptionHandler
Application.Run(New Form1)
End Sub
Private Sub UnhandledExceptionHandler(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
YourReportingMethod(CType(e.ExceptionObject, Exception))
End Sub
Private Sub ThreadExceptionHandler(ByVal sender As Object, ByVal e As Threading.ThreadExceptionEventArgs)
YourReportingMethod(e.Exception)
End Sub
Private Sub YourReportingMethod(e As Exception)
MessageBox.Show(e.Message)
Application.Exit
End Sub
End Module
The last method (you can give it any name you want) is your unexpected exception handler. Do whatever you want there. Log the exception in the event log, in a database or in a file. Report the exception in a mail message. Play some soothing music and apologize for your mistake. All of these.
Try
'Your code
Catch ex As SqlException
'SQL Exception handling
Catch ex As IO.EndOfStreamException
'Unexpected end of the file
Catch ex As IOException
'File Exception handling
Catch
Throw
End Try
The Catch...Throw at the end does the trick. It will send the Exception up the stack trace. If you terminate all your Try...Catch blocks that way, unhandled exceptions will always bubble up to your centralized error handling routine.
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (0)