momExMachina
momExMachina

Reputation: 111

Python code skips try/except clause

I am working on a class assignment in which I need to raise two exceptions. First Exception: I am supposed to raise and handle an exception if a user's entry is less than 0 or greater than 100. The code should then ask the user for the digit again.

Second Exception: If a particular file is not found, the exception requests the file name and then search happens again.

In both cases, I cannot make the exception happen. In other words, if in the first exception, I enter a digit greater than 100 or less 0, the program continues and simply doesn't record anything for this entry. If I print the user's entry, I get "none" rather than the error message that the except clause should display. Likewise in the second exception, if the file is not found, the code simply stops executing rather than firing the exception.

I have tried manually raising an exception (as in this question/answer), but that creates a traceback which I do not want-- I just want the first exception to print the error message and call a function and the second to request input and call a function.

First exception:

def grade():
    #input student's average grade
    avgGrade = int(input("Enter average grade: "))
    try:
        if avgGrade > 0 and avgGrade < 100:
            return avgGrade
    except ValueError:
        print("Grade must be numeric digit between 0 and 100")
        grade()

Second exception:

def displayGrades(allStudents):
    try:
        #open file for input
        grade_file = open(allStudents, "r")

        #read file contents
        fileContents = grade_file.read()

        #display file contents
        print(fileContents)

        grade_file.close()

    except IOError:
        print("File not found.")
        allStudents = input("Please enter correct file name: ")
        displayGrades(allStudents)

Upvotes: 1

Views: 3391

Answers (3)

Eslam Negida
Eslam Negida

Reputation: 1

Try this:

def get_value(data_list, index):
    return data_list[index]

# Sample list data
my_list = ['a', 'b', 'c']

Upvotes: 0

Shady Atef
Shady Atef

Reputation: 2401

For your first one, you have to raise it manually as python won't guess your logic and raise it for you.

def grade():
    #input student's average grade
    avgGrade = int(input("Enter average grade: "))
    try:
        if avgGrade > 0 and avgGrade < 100:
            return avgGrade
        else:
            raise ValueError()      
    except ValueError:
        print("Grade must be numeric digit between 0 and 100")
        return grade()

For the second one, You have to return the value in the second call. use return displayGrades(allStudents) instead of displayGrades(allStudents)

Upvotes: 1

AChampion
AChampion

Reputation: 30258

Sounds like the exercise is to raise the exception and handle it. You really need a loop for continuation rather than recursion, e.g.:

def grade():
    while True:
        try:
            avgGrade = int(input("Enter average grade: "))
            if avgGrade < 0 or avgGrade > 100:
                raise ValueError()
        except ValueError:
            print("Grade must be numeric digit between 0 and 100")
            continue # Loop again
        break # Exit loop
    return avgGrade

But this is contrived for the purpose of the exception, as exceptions are not really needed in this case.

For your other example this is less contrived because the downstream function raises the exception, e.g.:

def displayGrades(allStudents):
    while True:
        try:
            with open(allStudents, "r") as grade_file:
               ...
        except IOError:
            allStudents = input("Please enter correct file name: ")
            continue
        break

Though I would caution mixing arg passing and user input in the same function - usually the exception would be caught and handled where the user is originally providing the file name. So in this example, it would probably be the calling function.

Upvotes: 2

Related Questions