如何在异常消息中包含外部类?



我希望在使用内部类作为异常时获得更准确的异常消息。例如:

import csv
class CsvReader: # pylint: disable=too-few-public-methods
""" Handles reading of the CSV input file
"""
def __init__(self):
self.file_name = 'test.csv'
self.header = ''
def read_file(self):
""" Reads the CSV file.
"""
with open(self.file_name) as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
line_count = 0
for row in csv_reader:
if len(row) == 0:
continue
if len(row) != 5:
raise self.BadRowFormat(row, line_count)
if line_count == 0:
self.header = row.copy() # clone the list
line_count += 1
print(f'Processed {line_count} lines.')
class BadRowFormat(Exception):
""" Exception thrown when a line of the CSV file does not satisfy the
expected format
"""
def __init__(self, row, line_count):
super().__init__(f'Could not parse line {line_count}: {", ".join(row)}. '
f'Expected 5 fields, got {len(row)}')
def main():
""" Main function
"""
csv_reader = CsvReader()
csv_reader.read_file()

main()

和输入文件test.csv:

Name,Places,Adult price,Pensioner price,Children price
B1,50,100,60,50
B2,100,120,70,60
B3,150,125,75,60
1

当我运行这个脚本时,我得到以下异常消息:

File "./t.py", line 43, in <module>
main()
File "./t.py", line 40, in main
csv_reader.read_file()
File "./t.py", line 22, in read_file
raise self.BadRowFormat(row, line_count)
__main__.BadRowFormat: Could not parse line 4: 1. Expected 5 fields, got 1

是否有可能获得比:__main__.BadRowFormat更具描述性的异常消息?我希望有类似CsvReader.BadRowFormat__main__.CsvReader.BadRowFormat的东西,它将向用户显示异常源自CsvReader类。

您可以使用这种结构:

class BadRowFormat(Exception):
""" Exception thrown when a line of the CSV file does not satisfy the
expected format
"""
def __init__(self, classname, row, line_count):
super().__init__(f'{classname}: Could not parse line {line_count}: {", ".join(row)}. '
f'Expected 5 fields, got {len(row)}')

然后调用:

self.BadRowFormat(self.__class__.__name__, row, line_count)

这样可以在错误中添加类名。希望我正确理解了你的问题。

最新更新