Throwing exception?

qadeer37

Well-known member
Joined
May 1, 2010
Messages
63
Location
Hyderabad,pakistan
Programming Experience
1-3
VB.NET:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim obj As New Minimal
        Dim userAge As Integer
        userAge = CType(InputBox("Please enter your age"), Integer)

        MessageBox.Show(obj.Age.ToString)

    End Sub

Public Class Minimal
    Private m_Age As Integer
    Property Age() As Integer
        Get
            Age = m_Age
        End Get
        Set(ByVal value As Integer)
            If value < 0 Or value >= 100 Then

                Dim AgeException As New ArgumentException("Age must be within 0 to 100")
                Throw AgeException

            Else
                m_Age = value
            End If
        End Set
    End Property
End Class

Even if the user enter age more then 100 program doesn't halts. What I want to do is that if user enter an age above 100 an exception should be shown so that user is informed and without try catch. I think there must be some code in minimal class to do so.
 
Thanks it was a mistake but still after changing it if I enter age above 100 it doesn't shows messagebox but there is no exception shown as well to inform the user that obj.age has not been changed.
 
Throwing an exception is not like showing a friendly message to the user.
If you want to warn the user to enter a number in the given range you don't need to throw an exception at all.
Rather, just check the input and then if the criteria is not satisfied show the messagebox.

You don't need anything of those things ... instantiating class, property etc.
Just try this:
VB.NET:
If CType(InputBox("Please enter your age"), Integer) < 0 Or CType(InputBox("Please enter your age"), Integer) >= 100 Then
    MessageBox.Show("Age must be within 0 to 100")
End If
 
Back
Top