为了账号安全,请及时绑定邮箱和手机立即绑定

处理传播错误

处理传播错误

当年话下 2023-10-31 21:27:17
在我的代码中,我有一个主函数,它调用一个从文件中读取一些数据并返回该数据的函数,然后以不同的方式使用该数据。显然存在用户输入无法找到的文件名从而导致错误的风险。我想捕获此错误并输出我编写的错误消息,而无需回溯等。我尝试使用标准的 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
查看完整描述

3 回答

?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

因为main是一个函数,你可能return会出错:


def main(filename):

    try:

        x, y = getData(filename)

    except FileNotFoundError:

        print("file not found")

        return


    # calculations here


查看完整回答
反对 回复 2023-10-31
?
FFIVE

TA贡献1797条经验 获得超6个赞

以下


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,y



def 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,y

if __name__ == "__main__":

    main('get_the_file_name_from_somewhere.txt')


查看完整回答
反对 回复 2023-10-31
?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

解决方案

sys.exitSystemExit采用可选参数 - 0 被视为成功终止。

例子

sys.exit(0)
raise SystemExit(0)

参考

Python sys.exit:https://docs.python.org/3/library/sys.html#sys.exit


查看完整回答
反对 回复 2023-10-31
  • 3 回答
  • 0 关注
  • 89 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信