Tags

This event provides notification of uncaught exceptions. Below is the simple example:
The main form is just to call a exe which will throw exception and write to the event log

Imports System.Threading

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim runningPorcess As Process
        runningPorcess = StartProcess()
        CheckProcess(runningPorcess)
    End Sub

    Private Function StartProcess() As Process
        Dim ProcessInstance As New Process
        Dim processStartInfo As New System.Diagnostics.ProcessStartInfo

        Try


            processStartInfo.FileName = "C:\Documents and Settings\kenz\My Documents\Visual Studio 2005\Projects\ConsoleApplication1\JobRun\bin\Debug\JobRun.exe"
            processStartInfo.WindowStyle = ProcessWindowStyle.Normal
            ProcessInstance.StartInfo = processStartInfo
            ProcessInstance.Start()

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

        Return ProcessInstance
    End Function

    Private Sub CheckProcess(ByVal runningProcess As Process)
        If runningProcess.HasExited Then
            Thread.Sleep(20000)
            runningProcess.Start()
        End If
    End Sub
End Class

Here is the example to handle the UnhandledException

Imports System.Reflection.Emit
Imports System.Threading
Imports Microsoft.Win32

Public Class BatchJobRun
    Public Shared Sub Main()
        Dim currentDomain As AppDomain = AppDomain.CurrentDomain
        AddHandler currentDomain.UnhandledException, AddressOf UnhandledExceptionHandler

        Console.WriteLine("Hello World")
        Throw New Exception("I am killed")
    End Sub

    Private Shared Sub UnhandledExceptionHandler(ByVal sender As Object, ByVal args As UnhandledExceptionEventArgs)
        Using sw As New StringWriter()
            Dim e As Exception = CType(args.ExceptionObject, Exception)
            Console.WriteLine("MyHandler caught : " + e.Message)

            Try


                Dim log As System.Diagnostics.EventLog = EventLog.Create(EventLog.LogName)
                Diagnostics.EventLog.WriteEntry("BatchJobRun", sw.ToString, EventLogEntryType.Error)
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try
        End Using
    End Sub
End Class

Public Class EventLog
    Public Const LogName As String = "MyLog"

    Public Shared Function Create(ByVal sourceName As String) As System.Diagnostics.EventLog
        If Not System.Diagnostics.EventLog.SourceExists(sourceName) Then
            System.Diagnostics.EventLog.CreateEventSource(sourceName, LogName)
        End If

        Dim log As New System.Diagnostics.EventLog
        log.Source = sourceName
        log.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 14)
        Return log
    End Function
End Class
Advertisements