如何正确使用 raise?

How do I use raise correctly?

有人可以帮我在这段代码中获得某种结构吗?我是新来的。错误应该捕获不存在的文件,以及不包含由“;”分隔的四部分行的文件。

程序应如下所示:

测验文件名称:hejsan
"That resulted in an input/output error, please try again!"

测验文件名称:namn.csv
“文件格式不正确。 需要有四个字符串,用 ; 分隔在文件的每一行中。"

测验文件名称:quiz.csv

其中 quiz.csv 满足所有要求!

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()

您的代码中存在缩进错误

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()

您有很多问题:

  1. 在多个位置未能正确缩进
  2. 无法保留 split 的结果,因此您的长度测试是测试字符串的长度,而不是分号分隔的组件的数量
  3. (次要)不使用 with 语句,也不关闭文件,因此文件句柄可以无限期地打开(取决于 Python 解释器)

固定代码:

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()