简体   繁体   中英

How do I use custom exception in Python

I am new to Python and trying to use methods I don't totally understand yet (specifically the custom exception part).

In the below code snippet, I want the user to enter a username (as part of a registration process). I then want to validate this username for 2 things. Firstly just the format (re) then secondly I want to check if the username is already taken by referencing a file containing usernames and passwords.

Firstly, I know the entire way I am doing it is probably wrong. I am also curious why this method isn't working. What's currently happening is that it works correctly ONCE, ie if I use a username already taken it hits my custom exception and goes back and asks me to enter a username again. But from that point onwards the validation doesn't work - I can enter the exact same username again and it passes.

def register():
    uf = open("user.txt","r+")
    un = re.compile(r"[a-zA-Z]{3,10}$")  # Only allow a-z, 3-10 length, and check full string.
    up = re.compile(r".{3,10}$")  # Allow a-z, numbers and some special chars.
    class ExistException(Exception):
        pass
    print("Register new user:\n")

    # Get and validate username:
    while True:
        try:
            new_user = input("Please enter a username:\n-->") 
            assert un.match(new_user)
            for line in uf:
                existing_un = line.strip().split(", ")[0]  # Stores username in variable
                # Check variable against input from user:
                if new_user == existing_un:
                    raise ExistException()
        except AssertionError:
            print("That is not a valid username. \nOnly alpha characters are allowed (a - z)"
            ", and username must be between 3 and 10 characters.")   
        except ExistException:
            print("That username already exists")
        else:   
            break

I figured it out.

The for loop continued on from the line in the file it last left off on (where the existing username was found), so when the loop repeated it didn't check the same line again so didn't find the username.

Added "uf.seek(0)" to the "except" part of the code which resets the index so for loop starts again at line 1 of the file.

You never wrote the username that triggers the 1st exception to your file.

Close the file handle you opened because it's only in read mode. Then open it in append mode.

Note that if you open it write and not append mode that the file will be wiped clean first!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM