首页 > 解决方案 > “在处理上述异常期间,发生了另一个异常”

问题描述

我正在从文件中读取分数列表,并将它们解析为元组列表。如果文件为空或分母小于或等于 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:

标签: python-3.xexceptiontry-catch

解决方案


你的异常的主体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)

推荐阅读