处理传播错误

在我的代码中,我有一个主函数,它调用一个从文件中读取一些数据并返回该数据的函数,然后以不同的方式使用该数据。显然存在用户输入无法找到的文件名从而导致错误的风险。我想捕获此错误并输出我编写的错误消息,而无需回溯等。我尝试使用标准的 try- except 语句,该语句几乎按预期工作,除了现在未读取数据,因此当我尝试时出现新错误使用空变量进行计算。在异常块中使用sys.exitorraise SystemExit会导致在控制台中写入带有回溯的错误,并且捕获第一个错误的整个点感觉是多余的。我可以将整个程序包装在一个 try 语句中,但我从未见过这样做,而且感觉不对。如何以干净的方式终止程序或隐藏所有后续错误?

 def getData(fileName):

        try:

            file = open(fileName,"r")

            data = file.readlines()

            file.close()

            x = []

            y = []

            for i in data:

                noNewline = i.rstrip('\n')

                x.append(float(noNewline.split("\t")[0]))

                y.append(float(noNewline.split("\t")[1]))

            return x,y

        except FileNotFoundError:

            print("Some error messages")


    def main(fileName):

        x,y = getData(fileName)

        # diffrent calculations with x and y


当年话下
浏览 93回答 3
3回答

慕桂英4014372

因为main是一个函数,你可能return会出错:def main(filename):    try:        x, y = getData(filename)    except FileNotFoundError:        print("file not found")        return    # calculations here

FFIVE

以下def getData(fileName):    file = open(fileName,"r")    data = file.readlines()    file.close()    x = []    y = []    for i in data:        noNewline = i.rstrip('\n')        x.append(float(noNewline.split("\t")[0]))        y.append(float(noNewline.split("\t")[1]))    return x,ydef main(fileName):    # if you only want to handle exception coming from 'getData'    try:        x,y = getData(fileName)    except Exception as e:        print(f'could not get data using file {filename}. Reason: {str(e)}')        return    # do something with x,yif __name__ == "__main__":    main('get_the_file_name_from_somewhere.txt')

慕尼黑的夜晚无繁华

解决方案sys.exit并SystemExit采用可选参数 - 0 被视为成功终止。例子sys.exit(0) raise SystemExit(0)参考Python sys.exit:https://docs.python.org/3/library/sys.html#sys.exit
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python