Ok. Something I want in some of my applications, mainly web apps, is the ability for me to get an email when an unhandled exception is found, or any exception is found. So, here is some code I just hacked up as a test to show you how it works. Firstly, the actual exception handling code. The reason I made this into a function is because it will be called a lot in the web application, so a function will make life easer for me.


    Public Function EmailException(ByVal ex As Exception, ByVal sendto As String)

        Dim message As New MailMessage

        Dim server As String = "InsertServerHere" ‘ this is the server your mail will be sent though. Change this to your server

        Dim from As String = "InsertEmailHere" ‘ this is the email address the message will come from. Change this to your email address

        message.Subject = "Caught Exception: " & ex.Message

        message.From = from         message.BodyFormat = MailFormat.Html

        message.Body = ex.Message & "
" & ex.StackTrace

        message.To = sendto

        SmtpMail.SmtpServer = server


        MsgBox("caught exception and sent by email")

    End Function


As you can see in the function, it takes in the exception, and also an email address that the information will be sent to. There are some variables that need to be changed for this to work properly next is the test function I used. This is fairly basic. 2 input boxes take in 2 numbers and then return the value of the first one divided by the second one. I tried the first one as 4 and the second as 0 but no exception was thrown. It just returns infinity. So, then I tried 4 and h. the h caused an exception.


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


            Dim i As Integer = InputBox("enter a number")

            Dim j As Integer = InputBox("enter another number")

            MsgBox(i / j)

        Catch ex As Exception

            EmailException(ex, "insertemailaddresshere") ‘the email address is where the email will be sent to. Change this to suit

        End Try

    End Sub


So, hopefully this helps someone! Good luck and happy coding!