Python 未引发子类异常
应该读几行,包括姓名和姓氏,把每个学生的分数加起来,打印成字典: (约翰·史密斯5 安娜·博林4.5 约翰·史密斯2 安娜·博林(11) 我不明白为什么子类的“raise FileEmpty()”之外的文件中的FileEmpty在文件为空时没有被引发。它什么也不返回Python 未引发子类异常,python,exception,subclass,Python,Exception,Subclass,应该读几行,包括姓名和姓氏,把每个学生的分数加起来,打印成字典: (约翰·史密斯5 安娜·博林4.5 约翰·史密斯2 安娜·博林(11) 我不明白为什么子类的“raise FileEmpty()”之外的文件中的FileEmpty在文件为空时没有被引发。它什么也不返回 import os from os import strerror class StudentsDataException(Exception): pass class BadLine(StudentsDataExcep
import os
from os import strerror
class StudentsDataException(Exception):
pass
class BadLine(StudentsDataException):
def __init__(self):
Exception.__init__(self)
print("Bad line of data in file, terminating ...")
exit()
class FileEmpty(StudentsDataException):
def __init__(self):
Exception.__init__(self)
print("Empty file offered, terminating ...")
exit()
dict = {}
try:
fname = input("Source file name?: ")
src = open(fname, 'rt')
line = src.readline()
while len(line) != 0:
lst = line.split()
if(len(lst) < 3):
raise BadLine()
key = (lst[0], lst[1])
if key in dict:
dict[key] += float(lst[2])
else:
dict[key] = float(lst[2])
line = src.readline()
src.close()
for k, v in dict.items():
print(k, "-->", v)
except BaseException as e:
if(os.path.getsize(fname) == 0):
raise FileEmpty()
if(e == IOError):
print("I/O error occurred: ", strerror(e.errno))
if(e == ValueError):
print("Value error")
else:
print("Other error", strerror(e.errno))
导入操作系统
从操作系统导入strerror
班级学生数据异常(异常):
通过
班级基线(学生数据除外):
定义初始化(自):
例外情况。初始化(自我)
打印(“文件中的数据行错误,正在终止…”)
退出()
类文件为空(StudentsDataException):
定义初始化(自):
例外情况。初始化(自我)
打印(“提供了空文件,正在终止…”)
退出()
dict={}
尝试:
fname=input(“源文件名:”)
src=open(fname,'rt')
line=src.readline()
而len(line)!=0:
lst=line.split()
如果(len(lst)<3):
提高底线
键=(lst[0],lst[1])
如果输入dict:
dict[key]+=float(lst[2])
其他:
dict[key]=浮点(lst[2])
line=src.readline()
src.close()
对于目录项()中的k,v:
打印(k,“-->”,v)
除BaseException作为e外:
如果(os.path.getsize(fname)==0):
raisefileempty()
如果(e==IOError):
打印(“发生I/O错误:”,strerror(e.errno))
如果(e==ValueError):
打印(“值错误”)
其他:
打印(“其他错误”,strerror(e.errno))
你能试试os.stat(“文件”).st\u size==0吗?虽然我认为它们是相同的方法。是否已到达下除bseeexception as e:
之外的其他if语句?