Results 1 to 8 of 8

Thread: UnhandledException Doesn't Work

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Jun 2010
    Posts
    144

    UnhandledException Doesn't Work

    I'm trying to catch all the unhandled exceptions in my application with UnhandledException. My code is shown below. I understand that I have to build the application (Control F5) in release mode and run the exe file in the bin directory. But, that doesn't seem to be working. I don't get the MessageBox error. The WriteToErrorLog line writes the error to a txt file, but it doesn't do anything either. The WriteToErrorLog works fine in a Try Catch block. Any ideas why UnhandledException is not working for me? Do I need to add any code in another place in my project? Thanks in advance.

    Code:
    Namespace My
    
        Partial Friend Class MyApplication
    
            Private Sub MyApplication_UnhandledException(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
                
                Dim el As New ErrorLogger
                el.WriteToErrorLog(e.Exception.ToString, e.Exception.InnerException.ToString(), "Error, Unhandled Exception")
                MessageBox.Show(e.Exception.ToString & e.Exception.InnerException.ToString()) '<-- the exception object
                Console.WriteLine("error: " + e.Exception.ToString)
                e.ExitApplication = False '<-- True if you want the application to close; false to continue - if it can
    
            End Sub
    
        End Class
    
    End Namespace
    Code:
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
            'CODE TO CRASH PROGRAM And TEST UNHANDLED EXCEPTIONS
            Dim MyIVar As Integer = 1
            MyIVar /= 0
    
        End Sub

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    108,500

    Re: UnhandledException Doesn't Work

    The issue is that your exception handling code is throwing another exception. If you had paid attention in the debugger then you'd have seen that the InnerException for the exception you're throwing is Nothing. In that case, what do you think this is going to do:
    Code:
    e.Exception.InnerException.ToString()
    It's going to throw a NullReferenceException. The simple fix is to do this:
    Code:
    e.Exception.InnerException?.ToString()
    so that will evaluate to Nothing if there's no InnerException. A more robust solution might be something like this:
    vb.net Code:
    1. Dim ex = e.Exception
    2. Dim errorLog = ex.ToString()
    3.  
    4. While ex.InnerException IsNot Nothing
    5.     ex = ex.InnerException
    6.  
    7.     errorLog &= Environment.NewLine & ex.ToString()
    8. End While

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Jun 2010
    Posts
    144

    Re: UnhandledException Doesn't Work

    Nope, I didn't have any luck. I tried both codes below and it didn't work. I ran the exe file in the bin directory. Your original suggested code gave me an error, so I defined variable ex as an object. Not sure if that is correct.

    Code:
    Namespace My
    
        Partial Friend Class MyApplication
    
            Private Sub MyApplication_UnhandledException(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
                
                Dim el As New ErrorLogger
                el.WriteToErrorLog(e.Exception.ToString, e.Exception.InnerException?.ToString(), "Error, Unhandled Exception")
    
                MessageBox.Show(e.Exception.ToString & e.Exception.InnerException?.ToString()) '<-- the exception object
                Console.WriteLine("error: " + e.Exception.ToString)
                e.ExitApplication = False '<-- True if you want the application to close; false to continue - if it can
    
            End Sub
    
        End Class
    
    End Namespace
    Code:
    Namespace My
    
        Partial Friend Class MyApplication
    
            Private Sub MyApplication_UnhandledException(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
                
                Dim ex As Object = e.Exception
                Dim errorLog As String = ex.ToString()
    
                While ex.InnerException IsNot Nothing
                    ex = ex.InnerException
    
                    errorLog &= Environment.NewLine & ex.ToString()
                End While
    
                Dim el As New ErrorLogger
                el.WriteToErrorLog(e.Exception.ToString, e.Exception.InnerException?.ToString(), "Error, Unhandled Exception")
    
                MessageBox.Show(e.Exception.ToString & e.Exception.InnerException?.ToString()) '<-- the exception object
                Console.WriteLine("error: " + e.Exception.ToString)
                e.ExitApplication = False '<-- True if you want the application to close; false to continue - if it can
    
            End Sub
    
        End Class
    
    End Namespace

  4. #4
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    108,500

    Re: UnhandledException Doesn't Work

    There's a lot to address here but I just can't bear it right now. What I will suggest is that you take it back to basics, as you should have done from the start. Forget the InnerException for now and try just logging the exception itself. As you should ALWAYS do when things don;t work, simplify the code as much as possible and then add to it until it breaks to se where the issue is.

  5. #5
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    7,600

    Re: UnhandledException Doesn't Work

    It seems you want to be able to walk through all the exceptions on the call stack through use of the InnerException property. You need to do this recursively if you want to capture the data on all of them:-
    Code:
    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            AddHandler My.Application.UnhandledException, AddressOf EH_UnhandledException
    
            'Lets imitate an exception chain that typically comes
            'from multiple levels in the call stack.
            Dim ex As New Exception("Bombing out!", New Exception("Internal Bombout!", New Exception("Really deep error", New Exception("Now this is too deep!"))))
    
            Throw ex
        End Sub
    
        Private Sub EH_UnhandledException(ByVal sender As Object, ByVal e As ApplicationServices.UnhandledExceptionEventArgs)
            MessageBox.Show(ExceptionToSting(e.Exception))
        End Sub
    
        Private Function ExceptionToSting(ByVal e As Exception) As String
            'This function recursively walks the Exception chain.
            '***********************************************************
    
            Dim msg As String = e.Message & Environment.NewLine & Environment.NewLine
    
            If e.InnerException IsNot Nothing Then
                Return msg & ExceptionToSting(e.InnerException)
            Else
                Return msg
            End If
    
        End Function
    
    
    End Class
    Output:-
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  6. #6

    Thread Starter
    Addicted Member
    Join Date
    Jun 2010
    Posts
    144

    Re: UnhandledException Doesn't Work

    Niya, I tried that and it worked for me. The problem for me is that I'm trying to write the errors to a log file in the app directory, but that part is not working for me.

    After more research, I found out that there are three ways to deal with these unhandled errors. They are ApplicationDomain, System.Windows, and My.Application.UnhandledException. I'm using the following code and it works, but it send the error files to a weird hidden directory "C:\Users\user\AppData\Roaming\MyCompany\My". Now, I'm trying to figure out how to change the destination path. Microsoft has article about this, but it is clear as mud.

    Code:
    Namespace My
        Partial Friend Class MyApplication
    
            Private Sub MyApplication_UnhandledException(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
    
                My.Application.Log.WriteEntry("########  UNHANDLED EXCEPTION, WindowsFormsApplicationBase.UnhandledException Event  ########")
                My.Application.Log.WriteException(e.Exception, TraceEventType.Critical, "")
                My.Application.Log.DefaultFileLogWriter.ToString()
                My.Application.Log.WriteEntry(e.Exception.GetType.ToString())
                My.Application.Log.WriteEntry(e.Exception.StackTrace.ToString())
                My.Application.Log.WriteEntry(DateTime.Now.ToString())
                My.Application.Log.WriteEntry("-----------------------------------------------------------------------------------------------")
                e.ExitApplication = False
    
            End Sub
    
        End Class
    End Namespace

  7. #7
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,822

    Re: UnhandledException Doesn't Work

    You generally should not write to the app directory, and generally wont be able to - as Windows will block writing to protected folders (such as ProgramFiles etc), because that is what malware will do to infect programs etc.

    AppData is a standard place for things like log files, and there are some other folders that are potentially appropriate too depending on circumstances (such as MyDocuments and ProgramData).

    Here is some very old (Windows 2000) guidance on folder usage, which still applies today: https://docs.microsoft.com/en-us/pre...N#w2kcli_req42

  8. #8

    Thread Starter
    Addicted Member
    Join Date
    Jun 2010
    Posts
    144

    Re: UnhandledException Doesn't Work

    Well, I was able to do it. You need to add the following code to the app.config file in your project. All the unhandled errors are been sent to a directory "Errors" in my app bin directory.

    Code:
                    <listeners>
                        <add name="FileLog"/>
                    </listeners>
    Code:
            <sharedListeners>
                <!--NEXT LINE SENDS UNHANDLED ERRORS TO THE APP DIRECTORY ERRORS\APPNAME.LOG FILE-->
                <add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter" location="Custom" customlocation="Errors\" />
            </sharedListeners>

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width