How do I properly use try except in Python to validate student numbers?

I’m working on a program that processes student numbers and needs to categorize them as valid or invalid. A student number is considered valid if it has exactly eight digits and contains only numbers. Valid numbers should go into one list, invalid ones into another.

I want to understand how to apply the try except Python structure correctly for this scenario. I’m stuck on how to use it for checking each student number and handling exceptions where the input isn’t valid.

Here’s a simplified version of my current code structure.

Could someone guide me on how to complete the try except sections to handle the validation logic cleanly?

If anyone could help, I would greatly appreciate it!

Valid_file = "ValidNumbers.txt"
Invalid_file = "InvalidNumbers.txt"
Data_file = "Data.txt"

def analyse_students(Data_file):
    lenth = len(Data_file)
    total = 0
    try:
    
    except: 
    
    return 0
    
def read(Data_file):
    count = 0
    student_list = []
    try:
        open(Data_file)
    except:
        print("Couldn't append file", Valid_file)
    return count, student_list

def write(student, status):
    if status:
        try:
            open(Data_file)
        except:
            print("Couldn't append file", Invalid_file)
    
count, student_list = read(Data_file)

print("Number of lines read", count)

for student in student_list:

    print("See output files")

Hey @kusha.kpr I ran into a similar case when working with student ID validations last year.

The best way I found to use try except in this context is to treat potential type conversion errors explicitly.

Here’s how I handled it:

def is_valid_student_number(number):
    try:
        if len(number) == 8 and number.isdigit():
            return True
        else:
            return False
    except Exception as e:
        print(f"Error while checking number {number}: {e}")
        return False

In the loop where you process each student, just call this function and sort the numbers accordingly.

This way, your try block handles unexpected cases like None or non-string types gracefully. Hope this helps clarify things!

Hi there! I’ve handled this kind of logic in a data cleanup script for exam roll numbers.

What worked for me was using try not for validation logic directly but to catch any unexpected format or encoding issues from the file read.

Here’s a take on how I’d clean it up:

python
Copy
Edit
def analyse_students(data_file):
    valid_students = []
    invalid_students = []
    try:
        with open(data_file, 'r') as file:
            for line in file:
                student = line.strip()
                if student.isdigit() and len(student) == 8:
                    valid_students.append(student)
                else:
                    invalid_students.append(student)
    except IOError:
        print("Error reading file. Please check the path or permissions.")
    return valid_students, invalid_students

This lets try except do what it’s best at handling unexpected failures, while keeping your validation logic clean and explicit. Give it a go!