Results 1 to 20 of 20

Thread: [RESOLVED] IF..Catch and Class Exception

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Jan 2018
    Posts
    136

    Resolved [RESOLVED] IF..Catch and Class Exception

    Can someone tell me if I did this the right way so far?? I know im missing part of the IF..Catch statement still..Im working on that.

    Steps that I had to follow:

    1. Make the LoginException class a custom exception by deriving from the Exception class.
    2. In the Login procedure of the Main module, replace the two lines that read MessageBox.Show(“Incorrect password.”) with the following code: Throw New LoginException.
    3. Add a Try...Catch statement for the following line in the btnLogin_Click event handler procedure: Main.Login(txtUsername.Text, txtPassword.Text) Add the following line to the Catch block: MessageBox.Show(“Incorrect password.”)

    This is my LoginException code:

    Code:
    Public Class LoginException
        Inherits Exception
    End Class

    This is my Main.vb code

    Code:
    Module Main
        Friend blnLoggedIn As Boolean
        Dim arrUsernames() As String = {"Admin, Clerk, Manager"}
        Dim arrPasswords() As String = {"P@ssword, pa$$word, and passw0rd"}
    
        Sub Login(username As String, password As String)
            blnLoggedIn = False
            If VerifyUsername(username) And VerifyPassword(password) Then
                'Find index for username
                Dim userIndex As Integer
                For loopIndex = 0 To arrUsernames.Length - 1
                    If arrUsernames(loopIndex) = username Then
                        userIndex = loopIndex
                        Exit For
                    End If
                Next
                'Check for password match
                If arrPasswords(userIndex) = password Then
                    blnLoggedIn = True
                Else
                    Throw New LoginException
                End If
            End If
    
        End Sub
        Function VerifyUsername(username As String) As Boolean
            Return True
            'If the username is found, Return True, otherwise Return False
        End Function

    And this is my LoginForm code:

    Code:
    Public Class LoginForm
        Private Sub Label1_Click(sender As Object, e As EventArgs) Handles lblUsername.Click, btnLogin.Click
            Login(txtUsername.Text, txtPassword.Text)
            Try
            Catch ex As LoginException
                MessageBox.Show(“Incorrect password.”)
    
            End Try
            If Main.blnLoggedIn Then
                MessageBox.Show(“Thank you for logging in, “ & txtUsername.Text, “Logged In.”)
                Me.Close()
            End If
    
        End Sub
    
        Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
            Application.Exit()
        End Sub
    End Class

  2. #2
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,138

    Re: IF..Catch and Class Exception

    When using Try/Catch, you want the code that can trigger the exception to be inside of the Try statement. So you'll want to move the Login() statement after Try:

    Code:
            Try
                Login(txtUsername.Text, txtPassword.Text)
            Catch ex As LoginException
                MessageBox.Show(“Incorrect password.”)
            End Try

  3. #3
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,206

    Re: IF..Catch and Class Exception

    In the Login procedure of the Main module, replace the two lines that read MessageBox.Show(“Incorrect password.”) with the following code: Throw New LoginException.
    This says to replace 2 lines but you only have 1 line that says Throw New LoginException. I don't see another line in the Login procedure that says "Incorrect Password" so either the instructions are wrong or your Login procedure isn't written the way the instructor wanted.
    Last edited by wes4dbt; Jan 26th, 2018 at 02:58 PM.

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Jan 2018
    Posts
    136

    Re: IF..Catch and Class Exception

    Quote Originally Posted by OptionBase1 View Post
    When using Try/Catch, you want the code that can trigger the exception to be inside of the Try statement. So you'll want to move the Login() statement after Try:

    Code:
            Try
                Login(txtUsername.Text, txtPassword.Text)
            Catch ex As LoginException
                MessageBox.Show(“Incorrect password.”)
            End Try
    ok I did that but when I try to debug it says it cant debug because there are build errors..The login word keeps saying end of statement expected??

    Code:
    vate Sub Label1_Click(sender As Object, e As EventArgs) Handles lblUsername.Click, btnLogin.Click
            Try Login(txtUsername.Text, txtPassword.Text)
            Catch ex As LoginException
                MessageBox.Show(“Incorrect password.”)
            End Try

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

    Re: IF..Catch and Class Exception

    The word Try should be on a line by itself, as it was in OptionBase1's post.

    You then have one or more lines (in this case the Login(...) line) in between the Try line and the Catch line.

  6. #6

    Thread Starter
    Addicted Member
    Join Date
    Jan 2018
    Posts
    136

    Re: IF..Catch and Class Exception

    Quote Originally Posted by si_the_geek View Post
    The word Try should be on a line by itself, as it was in OptionBase1's post.

    You then have one or more lines (in this case the Login(...) line) in between the Try line and the Catch line.
    Oh ok thankyou for pointing that out!! I didnt think it mattered. I worked!

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    Jan 2018
    Posts
    136

    Re: IF..Catch and Class Exception

    Quote Originally Posted by OptionBase1 View Post
    When using Try/Catch, you want the code that can trigger the exception to be inside of the Try statement. So you'll want to move the Login() statement after Try:

    Code:
            Try
                Login(txtUsername.Text, txtPassword.Text)
            Catch ex As LoginException
                MessageBox.Show(“Incorrect password.”)
            End Try
    Ok so since I have updated my codes:


    This is my LoginForm code:

    Code:
    Public Class LoginForm
        Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
            Try
                Login(txtUsername.Text, txtPassword.Text)
            Catch ex As LoginException
                MessageBox.Show(“Incorrect password.”)
            End Try
            If Main.blnLoggedIn Then
                MessageBox.Show(“Thank you for logging in, “ & txtUsername.Text, “Logged In.”)
                Me.Close()
            End If
    
        End Sub
    
        Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
            Application.Exit()
        End Sub
    End Class

    This is my Main code:

    Code:
    Module Main
        Friend blnLoggedIn As Boolean
        Dim arrUsernames() As String = {"Admin", "Clerk", "Manager"}
        Dim arrPasswords() As String = {"P@ssword", "pa$$word", "passw0rd"}
        Dim userIndex As Integer
    
        Sub Login(username As String, password As String)
            blnLoggedIn = False
            If VerifyUsername(username) And VerifyPassword(password) Then
                blnLoggedIn = True
            Else
                Throw New LoginException
            End If
    
        End Sub
    
        Function VerifyUsername(username As String) As Boolean
            For loopIndex = 0 To arrUsernames.Length - 1
                If arrUsernames(loopIndex) = username Then
                    userIndex = loopIndex
                    Return True
                End If
            Next
            Return False
        End Function
    
        Function VerifyPassword(password As String) As Boolean
            'Check for password match
            If arrPasswords(userIndex) = password Then
                Return True
            Else
                Return False
            End If
        End Function
    
    End Module

    And this is my LoginException code:

    Code:
    Public Class LoginException
        Inherits Exception
    End Class
    Does everything look right to you for the set of instructions for this part??

  8. #8
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,138

    Re: IF..Catch and Class Exception

    Yes, that all looks like it correctly follows what the instructions are. Does it compile and properly handle valid and invalid usernames and password?

  9. #9
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,206

    Re: IF..Catch and Class Exception

    Reread Post #3

    My guess is that the instructor wants this "Throw New LoginException" in the VerifyUserName and VerifyPasswoord functions.

  10. #10

    Thread Starter
    Addicted Member
    Join Date
    Jan 2018
    Posts
    136

    Re: IF..Catch and Class Exception

    Quote Originally Posted by OptionBase1 View Post
    Yes, that all looks like it correctly follows what the instructions are. Does it compile and properly handle valid and invalid usernames and password?
    Yes it all works!! Now I have to make a new class with properties:


    The GroceryItem class should contain the following public properties:

    1. ScanNumber - Represents the unique serial code for the item on the shelf. This property should be read-only.

    2. BrandName - The name as described on the item’s packaging

    3. Description - A short description of the item

    4. Price - The amount of money it costs to buy the item. Make sure that only positive values can be assigned to this property.

    5. Aisle - This should indicate one of the following aisles: Bakery, CannedGoods, Drinks, Deli, DryGoods, FrozenFoods, and Produce.

    This is my Grocery Item code:

    Code:
    Public Class GroceryItem
       ReadOnly ScanNumber As Integer
        Property BrandName As String
        Property Description As String
        Property Price As Integer
        Property Aisle As String
    End Class
    It says you can use enumeration.

    The GroceryItem class should contain the following public constructors:

    1. A constructor that accepts and sets only the ScanNumber property. Remember: If a property is read-only, then you’ll need to set the variable, not use the property name.

    2. A constructor that accepts and sets the ScanNumber, BrandName and Price properties.

    Add a new public class named GroceryBasket to the project.

    1. Derive from the generic List class.
    2. Ensure that only GroceryItem objects are stored as items.

    Add the following variable declaration to the Main module: Friend basket As New GroceryBasket

    Main Code:
    Code:
    Module Main
        Friend blnLoggedIn As Boolean
        Dim arrUsernames() As String = {"Admin", "Clerk", "Manager"}
        Dim arrPasswords() As String = {"P@ssword", "pa$$word", "passw0rd"}
        Dim userIndex As Integer
        Friend basket As New GroceryBasket
    Test your work.

    Note: You can add code to the btnLogin_Click event handler procedure to instantiate the GroceryItem class and add multiple objects to the GroceryBasket variable. Make sure you either remove or comment out this code after testing.
    Last edited by EmilyM1105; Jan 26th, 2018 at 03:26 PM.

  11. #11
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,138

    Re: IF..Catch and Class Exception

    Creating a property for a class is much more involved than the code you included. I don't know what textbook (if any) your programming class is using, but you might want to take a look at this page for some basic examples of how properties are implemented in a Class: https://www.dotnetperls.com/property-vbnet

    That being said, you should start a new thread for this question.

  12. #12

    Thread Starter
    Addicted Member
    Join Date
    Jan 2018
    Posts
    136

    Re: IF..Catch and Class Exception

    ok i will

  13. #13
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: IF..Catch and Class Exception

    For some reason that page doesn't load for me, but actually making a property doesn't have to be involved.

    The traditional .NET property looks like this:
    Code:
    Private _backingField As TypeName
    
    Public Property PropertyName() As TypeName
        Get
            Return _backingField
        End Get
        Set(ByVal value As TypeName)
            _backingField = value
        End Set
    End Property
    'TypeName' above is any .NET type like String or Form or a type you make yourself. A .NET property is a weirdo syntax sugar for saying, "I want a thing that behaves like a variable, but gives me the option of executing some code when the value is set or retrieved".

    Having to type a minimum of 9 lines per property proved to get really old, really fast, as people started writing programs with hundreds of types and thus thousands of properties. It's especially tedious considering 99% of properties have the same implementation as the pattern above.

    So around the VS 2010 timeframe, "auto properties" were added to the compiler. If you type this:
    Code:
    Public Property PropertyName() As TypeName
    The compiler auto-generates the other 8 lines of code. You can also make a read-only auto-property:
    Code:
    Public ReadOnly Property PropertyName() As TypeName
    This can be set inline or during the constructor, and nowhere else.

    The problem is your assignment said it had to include "Public Properties". You didn't use the word "Public". That word is important, because it tells VB, "I'd like anything that has a GroceryItem to see these properties." When you don't use "Public", you get the default access specifier in VB. To find out what that is, you need to read the 200-page Visual Basic Language Specification. If that doesn't sound fun to you, then always make sure you put "Public", "Protected", "Private", or "Friend" in front of your properties. They each do different things, and any book/slides you have ought to explain the differences.

    Aside from that advice, I don't see a question in your post #10. I see you pasted your assignment, but the only question that implies is "do it for me". My answer is, "No, but if you are stuck on a part and can explain what you've tried, I will help you with that part."
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  14. #14
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,206

    Re: IF..Catch and Class Exception

    The problem is your assignment said it had to include "Public Properties". You didn't use the word "Public". That word is important, because it tells VB, "I'd like anything that has a GroceryItem to see these properties."
    Not sure you have to use the word "Public" anymore, in my VB 2015 test project the property is Public by default. Is would use it anyway, just as a matter of form but I don't believe it's required.

  15. #15

    Thread Starter
    Addicted Member
    Join Date
    Jan 2018
    Posts
    136

    Re: IF..Catch and Class Exception

    Quote Originally Posted by wes4dbt View Post
    Not sure you have to use the word "Public" anymore, in my VB 2015 test project the property is Public by default. Is would use it anyway, just as a matter of form but I don't believe it's required.
    Yea mine has it by default also

  16. #16
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,041

    Re: IF..Catch and Class Exception

    I wouldn't count on it, even if it is true. After all, if you get default wrong, then de fault is yours.
    My usual boring signature: Nothing

  17. #17
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: IF..Catch and Class Exception

    Quote Originally Posted by wes4dbt View Post
    Not sure you have to use the word "Public" anymore, in my VB 2015 test project the property is Public by default. Is would use it anyway, just as a matter of form but I don't believe it's required.
    If you don't use it, you have to read the Visual Basic Language Specification to know what the default is. It could be subject to change between versions of VB. In general, being explicit is more important than being fast.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

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

    Re: IF..Catch and Class Exception

    It also isn't just a matter of knowing what the default is, but what the default is in the current situation - because some situations have different defaults.

    Even if you know all the defaults, when reading the code you still need to think about which it is, and each time you do that it tends to waste more time than you saved from avoiding typing the extra word in the first place.

  19. #19
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,206

    Re: IF..Catch and Class Exception

    As I said, I would use it anyway and I always have. But it did surprise me that Public was the default. I went and checked the default for Subs and Functions in a class and again to my surprise they default to public. Learn something new every. Won't change how I write my code though. Has VB .Net always been this way?
    Last edited by wes4dbt; Jan 26th, 2018 at 05:02 PM.

  20. #20
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,206

    Re: IF..Catch and Class Exception

    Well, I tested VB 2010 and it behaves the same, don't have 2005 installed anymore. It just seems to me that MS would have them default to private, to keep code unexposed unless stated otherwise by using "Public".

Tags for this Thread

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