Search code examples
vb.netclasserror-handlinginitializer

How do you handle errors when calling another class initializer?


I am trying to do some error handling while also initializing new classes. I'm surprised at the way it is set up and am hoping that I'm just missing something very simple. Here's a simple version of what I'm trying to accomplish:

Public Class TestClass
    Public Sub New(ByVal sLink as String)
        Try
            Me.New(New Uri(sLink))
        Catch ex As Exception
            MessageBox.Show("Hey, initializing this class failed...  Is the URL valid?")
        End Try
    End Sub
    Public Sub New(ByVal uLink as Uri)
        MessageBox.Show("Class Initialized Successfully!")
    End Sub
End Class

The above obviously fails because the line with "Me.New(...)" must be the first line. I could do that however, what if somebody passes a string that is not a valid Uri? Consider the following:

' This would fail and I'd like to catch it somehow
Dim tmp as New TestClass("Hello World!")
' Something like this would pass successfully
Dim tmp as New TestClass("http://somevalidlink.com/")
' And so would this, too.
Dim tmp as New TestClass(New Uri("http://somevalidlink.com/")

I have been searching and can't seem to find anything... Maybe I just don't know the keywords to look for. Any hints in the right direction would be a great help.

Thanks!


Solution

  • I think you don't need to catch errors your class not responsible for.
    Instead check input parameter and throw exception if parameter is wrong.
    By throwing exception you will sure that class will work properly.

    Public Class TestClass
    
        Private _Link As Uri
    
        Public Sub New(ByVal link as Uri)
            If link Is Nothing Then Throw New ArgumentNullException(NameOf(link))
            _Link = link
        End Sub
    
    End Class
    

    If you want add feature to create instance by String parameter and still using constructor with parameter of type Uri, then you can create a static/shared method which check string and execute constructor you want.

    Public Shared Function CreateInstance(link As String) As TestClass
        Try
            Dim url As New Uri(link)
            Return New TestClass(url)
        Catch ex As Exception
            'Do your error handling
        End Try
    End Function