cowsay
cowsay

Reputation: 1332

Code jumps to Dispose() prematurely when using my class within a Using block

I have a custom class for handling errors in my application. Within it, I have a few methods for adding error details and generating/appending an error log. The code is very simple but I am puzzled by something.

I generate the error log by instancing my error handling class within a using block. After the code finishes executing the the first method, it jumps straight down to Dispose and that's it.

EDIT: Apparently I have not been clear enough.. removed my above example. Here's a stripped down version of my code:

Usage (read my notes):

Dim Message as String
Using Err as New ErrorHandler(ex,"Custom Message")
    Err.Add("Some detail about the error") <-- DOES THIS, THEN DISPOSES
    Err.Add("Another detail about the error") <--NEVER GETS EXECUTED
    Message = Err.WriteLog() <--NEVER GETS EXECUTED
End Using

ErrorHandler Class Contents:

Imports System.IO
Imports System.Text

Public Class ErrorHandler
    Implements IDisposable

    Public FriendlyMessage As String = String.Empty
    Public Exception As System.Exception = Nothing
    Private Messages As New List(Of String)

    Public Sub New(ByVal Exception As System.Exception, Optional ByVal FriendlyMessage As String = "")
        Me.Exception = Exception
        Me.FriendlyMessage = FriendlyMessage
    End Sub

    Public Sub Add(ByVal Message As String)
        Messages.Add(Message)
    End Sub

    Public Function WriteLog() As String
        ..... formats and writes to log file ..... 
        Return output
    End Function

    Private disposedValue As Boolean = False
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            ....... clean up ........
        End If
        Me.disposedValue = True
    End Sub

#Region " IDisposable Support "
    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region

End Class

Upvotes: 0

Views: 76

Answers (2)

Steven Doggart
Steven Doggart

Reputation: 43743

Change this:

Private Messages As List(Of String)

To this:

Private Messages As New List(Of String)()

You were not instantiating the list, so when you tried to add a message to the list, it threw a NullReferenceException. The unhandled exception would cause it to leave the Using block, which would call the Dispose method.

Upvotes: 0

Daniel
Daniel

Reputation: 11054

If I had to guess (which I have to do, since I don't know what the ErrorHandler class looks like), I'd say Messages has not been instantiated.

Upvotes: 1

Related Questions