将变量传递给异常?

时间:2016-10-07 02:10:40

标签: python exception

我正在尝试学习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?

3 个答案:

答案 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变量。例如,当staffIdstr而不是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