Search code examples
pythonfor-loopexceptionraise

How do I use raise correctly?


Can someone please help me to get some kind of structure in this code? I am new to this. The errors should capture both non-existing files, and files that do not contain rows of four parts separated by ";".

The program should look something like this:

Name of quiz-file: hejsan
"That resulted in an input/output error, please try again!"

Name of quiz-file: namn.csv
"The file is not on the proper format. There needs to be four strings, separated by ; in each line of the file."

Name of quiz-file: quiz.csv

Where quiz.csv fullfills all the requirements!

def get_quiz_list_handle_exceptions():
    success = True
    while success:
        try:

            file = input("Name of quiz-file: ")
            file2 = open(file,'r')

            for lines in range(0,9):
                quiz_line = file2.readline()
                quiz_line.split(";")

                if len(quiz_line) != 4:
                    raise Exception

    except FileNotFoundError as error:
        print("That resulted in an input/output error, please try again!", error)

    except Exception:
        print("The file is not on the proper format. There needs to be four strings, separated by ; in each line of the file.")

    else:
    success = False


get_quiz_list_handle_exceptions()

Solution

  • You have numerous issues:

    1. Failure to indent properly in several locations
    2. Failure to keep the results of split, so your length test is testing a string's length, not the number of semi-colon separated components
    3. (Minor) Not using with statements, nor closing your file, so the file handle could conceivably be left open indefinitely (depends on Python interpreter)

    Fixed code:

    def get_quiz_list_handle_exceptions():
        success = True
        while success:
            try:
    
                file = input("Name of quiz-file: ")
                with open(file,'r') as file2:  # Use with statement to guarantee file is closed
                    for lines in range(0,9):
                        quiz_line = file2.readline()
                        quiz_line = quiz_line.split(";")
    
                        if len(quiz_line) != 4:
                            raise Exception
    
            # All your excepts/elses were insufficiently indented to match the try
            except FileNotFoundError as error:
                print("That resulted in an input/output error, please try again!", error)
    
            except Exception:
                print("The file is not on the proper format. There needs to be four strings, separated by ; in each line of the file.")
            else:
                success = False  # Fixed indent
    
    
    get_quiz_list_handle_exceptions()