繁体   English   中英

如何正确使用 raise?

[英]How do I use raise correctly?

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

该程序应如下所示:

测验文件名称:hejsan
“导致输入/输出错误,请重试!”

测验文件名称: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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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