【问题标题】:"During handling of the above exception, another exception occurred"“在处理上述异常期间,发生了另一个异常”
【发布时间】:2019-09-25 18:27:44
【问题描述】:

我正在从文件中读取分数列表,并将它们解析为元组列表。如果文件为空或分母小于等于 0,我希望发生错误。

我尝试将if(EOFERRor)elif(zerodivisionerror)elif(assertionerror)else.. 放在InvalidFile(Exception) 类中。在我的异常会在文件读取结束时引发之前,这就是我专门将其包含在其中的原因。

我的猜测是 EOF 与除以零同时发生,但我将列表与文件分开以防止这种情况发生

class InvalidFile(Exception):

    if(EOFError):
        pass
    else:
        print('Invalid file format')
        sys.exit(1)

def createFractionList(filePath):    
    try:
        f = open(inFile)
        f.close()
    except FileNotFoundError:
        print('FileNotFoundError')
        sys.exit(1)

    fractionList = []
    for line in open(filePath):
        line = line.rstrip()
        try:
            numerator, denominator = tuple(int(x) for x in line.split())
        except:
            raise InvalidFile
        fractionList.append((numerator, denominator))
    for lists in fractionList:
       try:
            lists[0]/lists[1]
       except:
           raise InvalidFile
    return fractionList

dateList = createFractionList(inFile)
print(dateList)

输入:

1 0

3 4

5 6

7 8

9 10

0 8

2 4

9 12

20 24

35 40

54 60

预期输出:

Invalid file format

实际输出:

C:\Users\Xavier\PycharmProjects\hw4\venv\Scripts\python.exe C:/Users/Xavier/PycharmProjects/hw4/hw4.py
Traceback (most recent call last):
  File "C:/Users/Xavier/PycharmProjects/hw4/hw4.py", line 33, in createFractionList
    lists[1]/0
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

【问题讨论】:

  • 如何调用代码? except: 是不好的做法;你应该例如except ValueError: 或您真正想要捕获的任何异常。
  • 请问您,为什么要这样做“lists[1]/0”?
  • @hiroprotagonist 我以前有它:assert 1 / denominator except AssertionError: 但我把它拿出来是因为我不确定这是否是原因。我添加了我如何调用代码
  • @TonyJafar lists[1] / 0 是引用创建的元组的第二个值,即分母。
  • 所以你的意思是写lists[1] / lists[0](或者反过来?)

标签: python-3.x exception try-catch


【解决方案1】:

InvalidFile 异常的主体什么也不做,因为它只在声明时运行。无论如何,if EOFError 总是正确的,所以什么也没有发生。您应该做的是用自定义文本覆盖 __init__ 方法。我个人认为您不需要自定义异常,您可以使用内置异常。

您的第一个错误是FileNotFoundError,最好使用os.path.exists() 检查。

您应该在打开文件时使用上下文管理器,然后您不必担心关闭它。

您不需要删除该行,因为 `int('1 \n') 已经删除了空格。但也许输入文件有空行,所以我们可以保留它。

您不需要遍历文件然后遍历列表,因为如果在任何时候,分母小于或等于 0,就会引发错误。将错误延迟到以后是没有意义的。而且似乎没有必要进行除法,因为如果它会失败,您可以提前解决。

总而言之,您可以像这样重写代码:

import os.path

def create_fraction_list(file_path):
  if not os.path.exists(file_path):
    raise FileNotFoundError(file_path)
  fraction_list = []
  with open(file_path) as f:
    for line in f:
      line = line.strip()
      if not line:
        # have a blank line
        continue
      numerator, denominator = (int(x) for x in line.split())
      if denominator <= 0:
        raise ValueError(f'Denominator less that or equal to 0: {numerator}/{denominator}')
      fraction_list.append((numerator, denominator))
  if not fraction_list:
    # it's empty
    raise ValueError(f'Input file has no valid lines: {file_path}')
  return fraction_list

if __name__ == '__main__':
  try:
    fraction_list = create_fraction_list(inFile)
    print(fraction_list)
  except (FileNotFoundError, ValueError):
    print('Invalid file format.')
    sys.exit(1)

【讨论】:

    猜你喜欢
    • 2018-08-01
    • 1970-01-01
    • 2021-11-08
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 2019-03-14
    相关资源
    最近更新 更多