我正在尝试学习Python,我想知道是否可以将变量传递给Exception
?这是我的代码:
try:
staffId = int(row['staffId'])
openingSalary = int(row['initialSalary'])
monthsWorked = float(row['monthsWorked'])
except CutomException:
pass
class CustomException(ValueError): # raised if data conversion fails
def __init__(self):
print("There was a problem converting data")
我想将staffId
传递给异常,以便我可以打印如下内容:
print(“转换员工ID数据时出现问题:”,staffId)
我尝试了这个但没有成功:How to pass a variable to an exception when raised and retrieve it when excepted?
答案 0 :(得分:1)
例外的来电者,例如raise
异常必须将参数传递给构造函数的那个。
class CustomException(ValueError): # raised if data conversion fails
def __init__(self, message):
self.message = message;
print("There was a problem converting data")
try:
try:
staffId = int(row['staffId'])
openingSalary = int(row['initialSalary'])
monthsWorked = float(row['monthsWorked'])
except ValueError as e:
raise CutomException(e);
except CutomException:
pass
答案 1 :(得分:1)
自定义异常需要raise
阻止try
阻止包含staffId
变量。例如,当staffId
是str
而不是int
时。
try:
# conditionalize a scenario where you'd want to raise an error
# (e.g. the variable is a string)
if type(staffId) is str:
raise CustomException(staffId)
else:
staffId = int(row['staffId'])
openingSalary = int(row['initialSalary'])
monthsWorked = float(row['monthsWorked'])
except CutomException:
pass
class CustomException(ValueError): # raised if data conversion fails
def __init__(self, id):
print("There was a problem converting data %s" % id)
答案 2 :(得分:0)
我认为您应该在except块中而不是在异常类中处理异常。
wscript.echo GetLastMonday & "," & GetLastSaturday
for /f "tokens=1,2 delims=," %%A in ('cscript //nologo lastweek.vbs') do @echo %%A %%B