异常后如何继续程序?

时间:2020-07-24 12:01:36

标签: python file exception file-read

我应该从两个文件中读取。一个包含数字(其中混有无效字符),另一个包含运算符。程序在达到异常后停止,但是我需要它来继续读取数字文件。我尝试过pass关键字没有运气。

try:
    with open('numbers.txt') as file1, open('operators.txt') as file2:
        for no1, no2, op in itertools.zip_longest(file1, file1, file2):
            result = eval(no1.rstrip() + op.rstrip() + no2.rstrip())
            print(no1.rstrip() + op.rstrip() + no2.rstrip() + ' = ' + str(result))
except IOError:
    print('File cannot be found or opened')
    exit()
except ZeroDivisionError:
    print(no1.rstrip() + op.rstrip() + no2.rstrip() + ' - Division by 0 is not allowed')
except NameError:
    print(no1.rstrip() + op.rstrip() + no2.rstrip() + ' - Cannot perform operation with characters')

我将非常感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您可以将continuepass语句添加到except块中。将异常抛出循环,并添加continuepass语句。选中此Answer以供参考。

答案 1 :(得分:0)

拆分try-except块并将可忽略的错误移至for循环内:

import itertools

try:
    with open('numbers.txt') as file1, open('operators.txt') as file2:
        for no1, no2, op in itertools.zip_longest(file1, file1, file2):
            try:
                result = eval(no1.rstrip() + op.rstrip() + no2.rstrip())
                print(no1.rstrip() + op.rstrip() + no2.rstrip() + ' = ' + str(result))
            except ZeroDivisionError:
                print(no1.rstrip() + op.rstrip() + no2.rstrip() + ' - Division by 0 is not allowed')
            except NameError:
                print(no1.rstrip() + op.rstrip() + no2.rstrip() + ' - Cannot perform operation with characters')
except IOError:
    print('File cannot be found or opened')
    exit()